2009-05-27 18 views
3

我想使用GDI +在後臺線程上渲染圖像。我發現this example關於如何使用GDI +旋轉圖像,這是我想要做的操作。GDI +:如何將Graphics對象渲染爲後臺線程上的位圖?

private void RotationMenu_Click(object sender, System.EventArgs e) 
{ 
    Graphics g = this.CreateGraphics(); 
    g.Clear(this.BackColor); 
    Bitmap curBitmap = new Bitmap(@"roses.jpg"); 
    g.DrawImage(curBitmap, 0, 0, 200, 200); 

    // Create a Matrix object, call its Rotate method, 
    // and set it as Graphics.Transform 
    Matrix X = new Matrix(); 
    X.Rotate(30); 
    g.Transform = X; 

    // Draw image 
    g.DrawImage(curBitmap, 
    new Rectangle(205, 0, 200, 200), 
     0, 0, curBitmap.Width, 
     curBitmap.Height, 
     GraphicsUnit.Pixel); 

    // Dispose of objects 
    curBitmap.Dispose(); 
    g.Dispose(); 
} 

我的問題有兩個部分:

  1. 你將如何完成this.CreateGraphics()在後臺線程?可能嗎?我的理解是這個例子中的UI對象是this。所以如果我在後臺線程上做這個處理,我將如何創建一個圖形對象?

  2. 然後,我會如何從我正在使用的圖形對象中提取一個位圖,一旦完成處理?我一直無法找到一個如何做到這一點的好例子。


另外:格式化代碼示例時,我該如何添加新行?如果有人可以給我留言,說明我真的很感激。謝謝!

回答

12

要繪製位圖,您不想爲UI控件創建一個Graphics對象。創建使用FromImage方法的位圖Graphics對象:

Graphics g = Graphics.FromImage(theImage); 

一個Graphics對象不包含您繪製它的圖形,而不是它只是借鑑其他畫布,這通常是一個工具屏幕,但它也可以是一個Bitmap對象。

所以,你不畫,然後再提取位圖,首先要創建位圖,然後創建Graphics對象繪製它:

Bitmap destination = new Bitmap(200, 200); 
using (Graphics g = Graphics.FromImage(destination)) { 
    Matrix rotation = new Matrix(); 
    rotation.Rotate(30); 
    g.Transform = rotation; 
    g.DrawImage(source, 0, 0, 200, 200); 
} 
+0

啊,這很有趣。這絕對清除了一些謎團。我會嘗試的。謝謝! – 2009-05-27 18:40:57