GDI+:如何将Graphics对象渲染到后台线程的位图中?

3

我想使用GDI+在后台线程上渲染图像。我找到了这个示例,它演示了如何使用GDI+旋转图像,这正是我想要的操作。

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. 完成处理后,如何从正在使用的 Graphics 对象中提取位图?我找不到一个很好的示例来说明如何做到这一点。


另外:当格式化代码示例时,如何添加换行符?如果有人能给我留言解释一下,我会非常感激的。谢谢!

1个回答

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接