Using FormattedText to create a Bitmap

2020-04-20 09:17发布

In a C# forms project, I can write the following code to get something like what I want, but it seems that there are two different "worlds" that I am trying to fuse.

FormattedText text = new FormattedText(textBox1.Text, CultureInfo.GetCultureInfo("en-us"), System.Windows.FlowDirection.LeftToRight, new Typeface("Tahoma"), 20, System.Windows.Media.Brushes.Black);
text.MaxTextWidth = 480;
text.MaxTextHeight = 480;
DrawingVisual d = new DrawingVisual();
DrawingContext d1 = d.RenderOpen();
d1.DrawText(text, new System.Windows.Point(0, 0));
d1.Close();
RenderTargetBitmap bmp = new RenderTargetBitmap(480, 480, 120, 96, PixelFormats.Pbgra32);
bmp.Render(d);
System.Windows.Controls.Image I=new System.Windows.Controls.Image();
I.Source = bmp;

Gets me a Windows.Media.ImageSource. I want to migrate the whole thing to use the System.Drawing namespace.

Since I basically had to import WPF libraries to make the above code work, and what I am looking to do is so basic, how can I do it in Windows Forms, preferably in a non-cludgy way.

Note: All I really want to do is draw text on a bitmap in a way that allows line wrapping, and then manipulate it as a bitmap. If there is a simpler way of doing that (in Windows Forms) that would work just as well, if not better.

1条回答
祖国的老花朵
2楼-- · 2020-04-20 09:56

Yes, that's WPF code, an entirely different world. The System.Drawing version ought to resemble something like this:

var bmp = new Bitmap(480, 480);
using (var gr = Graphics.FromImage(bmp)) {
    gr.Clear(Color.White);
    TextRenderer.DrawText(gr, textBox1.Text, this.Font, 
        new Rectangle(0, 0, bmp.Width, bmp.Height), 
        Color.Black, Color.White,
        TextFormatFlags.WordBreak | TextFormatFlags.Left);
}
if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
pictureBox1.Image = bmp;

I guessed at a picture box on the form.

查看更多
登录 后发表回答