2012-01-05 76 views
1

在一個C#窗體項目中,我可以編寫下面的代碼來獲得我想要的內容,但似乎有兩個不同的「世界」,我試圖融合。使用FormattedText創建位圖

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窗體中),即使不是更好,也可以工作。

回答

3

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

我猜對了窗體上的一個圖片框。