gpt4 book ai didi

c# - 使用 FormattedText 创建位图

转载 作者:行者123 更新时间:2023-11-30 17:25:35 30 4
gpt4 key购买 nike

在 C# 表单项目中,我可以编写以下代码来获得我想要的东西,但似乎我试图融合两个不同的“世界”。

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 命名空间。

由于我基本上必须导入 WPF 库才能使上述代码工作,并且我想要做的事情非常基本,所以我如何在 Windows 窗体中完成它,最好以一种不笨拙的方式。

注意:我真正想做的是以允许换行的方式在位图上绘制文本,然后将其作为位图进行操作。如果有一种更简单的方法(在 Windows 窗体中),即使不是更好,也同样有效。

最佳答案

是的,这就是 WPF 代码,一个完全不同的世界。 System.Drawing 版本应该类似于这样:

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;

我猜到了表单上的图片框。

关于c# - 使用 FormattedText 创建位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27027322/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com