我想使用 GDI+ 在后台线程上渲染图像。我找到了 this example关于如何使用 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();
}
我的问题分为两部分:
您将如何在后台线程上完成
this.CreateGraphics()
?是否可以?我的理解是,在这个例子中,UI 对象是this
。因此,如果我在后台线程上执行此处理,我将如何创建图形对象?处理完成后,我该如何从正在使用的 Graphics 对象中提取位图?我还没有找到一个很好的例子来说明如何做到这一点。
另外:格式化代码示例时,如何添加换行符?如果有人可以给我留言解释我将非常感激。谢谢!
最佳答案
要在位图上绘图,您不想为 UI 控件创建 Graphics
对象。您使用 FromImage
方法为位图创建一个 Graphics
对象:
Graphics g = Graphics.FromImage(theImage);
Graphics
对象不包含您向其绘制的图形,它只是在另一个 Canvas (通常是屏幕)上绘制的工具,但也可以是 位图
对象。
因此,您不是先绘制再提取位图,而是先创建位图,然后创建 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);
}
关于c# - GDI+:如何在后台线程上将 Graphics 对象渲染为位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/917294/