Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8595729
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T00:30:30+00:00 2026-06-12T00:30:30+00:00

I am trying to create some rotated text and save that image to a

  • 0

I am trying to create some rotated text and save that image to a PNG file. The resulting PNG should be no larger than needed (or minimal padding). I have it working as long as there is no rotation, but as soon as I rotate the text, it is getting clipped off in the file. I am sure it has something to do with adjusting the either the CenterX and CenterY of the RotateTransform or creating a TranslateTransform, but I can’t find anything on how to do it correctly and my trial-and-error testing has turned into trial-and-frustration.

My sample code is below. I looking for a solution that would work with an arbitrary angle and not just -45 degrees.

Finally, if someone knows how to meet these requirements, but say using an “old style” Graphics object instead of WPF tools, I am open to that solution to that too.

private static void CreateImageFile()
{
    FormattedText ft;
    Geometry textBox;
    string fontName;
    Typeface face;
    DrawingVisual viz;
    RotateTransform rt;
    TranslateTransform tt;
    Rect rect;
    RenderTargetBitmap bmp;
    PngBitmapEncoder encoder;

    ft = CreateText("Lorem ipsum dolor sit amet, consectetur adipisicing" + Environment.NewLine + "elit, sed do eiusmod tempor", "Verdana", 12, false, false);
    textBox = ft.BuildHighlightGeometry(new Point());

    fontName = "Arial";
    face = new Typeface(fontName);

    // now create the visual we'll draw them to
    viz = new DrawingVisual();
    rt = new RotateTransform() { Angle = -45 };
    rect = rt.TransformBounds(ft.BuildHighlightGeometry(new Point(0, 0)).Bounds);

    using (DrawingContext dc = viz.RenderOpen())
    {
        dc.PushTransform(rt);
        dc.DrawText(ft, new Point(0, 0));
        dc.Pop();
    }

    bmp = new RenderTargetBitmap((int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Pbgra32);
    bmp.Render(viz);

    encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bmp));
    using (FileStream file = new FileStream("TextImage.png", FileMode.Create))
        encoder.Save(file);
}

private static FormattedText CreateText(string text, string typeface, double fontSize, bool bold, bool italic)
{
    FontStyle fontStyle = FontStyles.Normal;
    FontWeight fontWeight = FontWeights.Medium;

    if (bold == true) fontWeight = FontWeights.Bold;
    if (italic == true) fontStyle = FontStyles.Italic;

    // Create the formatted text based on the properties set.
    FormattedText formattedText = new FormattedText(
        text,
        CultureInfo.CurrentCulture,
        FlowDirection.LeftToRight,
        new Typeface(new FontFamily(typeface),
            fontStyle,
            fontWeight,
            FontStretches.Normal),
        fontSize,
        Brushes.Black, // This brush does not matter since we use the geometry of the text. 
        null,
        TextFormattingMode.Display
        );

    return formattedText;
}

Update

Based upon some of the suggestions below, I decided to try a different tack and experiment in the GUI. I created a window like this:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="160" Width="160" Loaded="Window_Loaded">
    <Grid>
        <Canvas Name="WorkCanvas" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock RenderTransformOrigin="0.5,0.5">
                <TextBlock.RenderTransform>
                    <TransformGroup>
                        <ScaleTransform/>
                        <SkewTransform/>
                        <RotateTransform Angle="-45"/>
                        <TranslateTransform/>
                    </TransformGroup>
                </TextBlock.RenderTransform>This is a test</TextBlock>
        </Canvas>
    </Grid>
</Window>

As you can see, it uses both the RotateTransform and the suggested RenderTransformOrigin, and the result is like the image below. And, as you can see, the text does not go through the middle of the Canvas. And that seems to be my entire problem. How to rotate the text and get it correctly centered.

Example


Update 2

I decided to try a Grid instead of a Canvas this time and I can now get the text properly centered in the grid, but since I can’t use a FormattedText object, I can’t seem to measure the actual bounding box. All measurements of the TextBlock or the Grid come back as if it was not rotated at all (looking at ActualWidth, ActualHeight, and DesiredSize). If I can’t get the rotated bounding box size, I can’t save the PNG without it getting clipped.

Oh, and I tried rotating the text in an unrotated grid and rotating the grid itself, both give the same results when trying to determine the dimensions.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T00:30:31+00:00Added an answer on June 12, 2026 at 12:30 am

    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.

    Phew!

    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);
    }
    

    Of course this is just a sample (but working) method and the final one will be parameterized.

    Final part of the puzzle was found at WPF: Getting new coordinates after a Rotation

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to create some div (that should be buttons) that have rounded
I am trying to create some top-to-text that will look similar to this, T
I'm trying to create some tests for a web services that implements CORS. So,
Im trying to create some moving div, actually remake one, so that div would
So I'm trying to create some scripts that I want to run without manually
I want to repeat a background image that is rotated. Trying to make it
I'm trying to create some OS X like text inputs for my website. They've
I am trying to create some capacity planning reports and one of the requrements
So I'm trying to create some graphs using Core Plot, but for the following
I am trying to create some reusable components in Silverlight2 . The difficulty comes

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.