【问题标题】:Using FormattedText to create a Bitmap使用 FormattedText 创建位图
【发布时间】:2012-02-03 19:07:13
【问题描述】:

在 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 窗体中),即使不是更好,也会同样有效。

【问题讨论】:

    标签: c# winforms bitmap


    【解决方案1】:

    是的,那是 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;
    

    我猜到了表格上的一个图片框。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多