Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>After much poking around and with help from Matt and kbo4sho88, I finally found the correct way of doing it. In addition to the help from the other posters, I finally found that I need to call TransformToVisual and TransformBounds to get the bounding box that I need for the correct file size. But, before that, I had to call Measure and Arrange since these objects are not shown on a screen.</p> <p>Phew!</p> <pre><code>private static void CreateImageFile() { Grid workGrid; TextBlock workTextBlock; RenderTargetBitmap bitmap; PngBitmapEncoder encoder; Rect textBlockBounds; GeneralTransform transform; workGrid = new Grid() { VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; workTextBlock = new TextBlock() { Text = "Lorem ipsum dolor sit amet, consectetur adipisicing" + Environment.NewLine + "elit, sed do eiusmod tempor", FontFamily = new FontFamily("Verdana"), FontSize = 36, TextAlignment = TextAlignment.Center, RenderTransformOrigin = new Point(0.5, 0.5), LayoutTransform = new RotateTransform(-45) }; workGrid.Children.Add(workTextBlock); /* * We now must measure and arrange the controls we just created to fill in the details (like * ActualWidth and ActualHeight before we call TransformToVisual() and TransformBounds() */ workGrid.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); workGrid.Arrange(new Rect(0, 0, workGrid.DesiredSize.Width, workGrid.DesiredSize.Height)); transform = workTextBlock.TransformToVisual(workGrid); textBlockBounds = transform.TransformBounds(new Rect(0, 0, workTextBlock.ActualWidth, workTextBlock.ActualHeight)); /* * Now, create the bitmap that will be used to save the image. We will make the image the * height and width we need at 96DPI and 32-bit RGBA (so the background will be transparent). */ bitmap = new RenderTargetBitmap((int)textBlockBounds.Width, (int)textBlockBounds.Height, 96, 96, PixelFormats.Pbgra32); bitmap.Render(workGrid); encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); using (FileStream file = new FileStream("TextImage.png", FileMode.Create)) encoder.Save(file); } </code></pre> <p>Of course this is just a sample (but working) method and the final one will be parameterized.</p> <p>Final part of the puzzle was found at <a href="https://stackoverflow.com/questions/581837/wpf-getting-new-coordinates-after-a-rotation">WPF: Getting new coordinates after a Rotation</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload