title: How can I render text on a WriteableBitmap on a background thread, in Windows Phone 7?
body: <p>I am trying to render text on a bitmap in a Windows Phone 7 application.</p>
  
  <p>Code that looks more or less like the following would work fine when it's running on the main thread:</p>
  
  <pre><code>public ImageSource RenderText(string text, double x, double y)
  {
      var canvas = new Canvas();
  
      var textBlock = new TextBlock { Text = text };
      canvas.Children.Add(textBloxk);
      Canvas.SetLeft(textBlock, x);
      Canvas.SetTop(textBlock, y);
  
      var bitmap = new WriteableBitmap(400, 400);
      bitmap.Render(canvas, null);
      bitmap.Invalidate();
      return bitmap;
  }
  </code></pre>
  
  <p>Now, since I have to render several images with more complex stuff, I would like to render the bitmap on a background thread to avoid an unresponsive UI.</p>
  
  <p>When I use a <code>BackgroundWorker</code> to do so, the constructor for <code>TextBlock</code> throws an <code>UnauthorizedAccessException</code> claiming that this is an invalid cross-thread access.</p>
  
  <p>My question is: how can I render text on a bitmap without blocking the UI?</p>
  
  <ul>
  <li>Please don't suggest using a web service to do the rendering. I need to render a large number of images and the bandwidth cost is not acceptable for my needs, and the ability to work offline is a major requirement.</li>
  <li>The solution doesn't necessarily has to use <code>WriteableBitmap</code> or <code>UIElements</code>, if there is another way to render text.</li>
  </ul>
  
  <p><strong>EDIT</strong></p>
  
  <p>Another thought: does anyone know if it should be possible to run a UI message loop in another thread, and then have that thread do the work? (instead of using a <code>BackgroundWorker</code>)?</p>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>To consider alternatives to <code>WriteableBitmap</code>, the features I need are:</p>
  
  <ul>
  <li>Draw a background image.</li>
  <li>Measure the width and height of a 1-line string, given a font familiy and size (and preferably style). No need for word wrapping.</li>
  <li>Draw a 1-line string, with given font family, size, style, at a given coordinate.</li>
  <li>Text rendering should support a transparent background. I.e. you should see the background image between the characters.</li>
  </ul>