GDI +:如何在背景线程上将Graphics对象渲染为位图?

我想使用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对象。 因此,如果我在后台线程上进行此处理,我将如何创建图形对象?

  2. 一旦我完成处理,我将如何从我正在使用的Graphics对象中提取位图? 我无法找到一个如何做到这一点的好例子。


另外:格式化代码示例时,如何添加换行符? 如果有人能给我发表评论,说明我真的很感激。 谢谢!

要绘制位图,您不希望为UI控件创建Graphics对象。 您可以使用FromImage方法为位图创建Graphics对象:

 Graphics g = Graphics.FromImage(theImage); 

Graphics对象不包含您绘制到它的图形,而只是它在另一个canvas上绘制的工具,通常是屏幕,但它也可以是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); }