使用FormattedText创建位图 [英] Using FormattedText to create a Bitmap

查看:163
本文介绍了使用FormattedText创建位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个C#形式的项目,我可以写出如下code得到像我想要什么,但似乎有两个不同的世界,我想融合。

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;

获取我 Windows.Media.ImageSource 。我要迁移的整个事情要使用 System.Drawing中命名空间。

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

因为我基本上不得不进口WPF库作出上述code的工作,我所希望做的是如此基本,我怎么能做到这一点在Windows窗体,preferably在非cludgy方式。

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.

注意:所有我真正想要做的是汲取的方式,允许换行的位图文字,然后操纵它作为一个位图。如果这样做,(在Windows窗体),将,如果没有更好的工作一样的简单的方法。

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.

推荐答案

是的,这是WPF code,一个完全不同的世界。该System.Drawing中的版本应该像这样的:

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.

这篇关于使用FormattedText创建位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆