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();
}
我的问题有两个部分:
如何在后台线程上完成
this.CreateGraphics()
? 是否可以? 我的理解是,在此示例中,UI 对象是this
。 因此,如果我在后台线程上执行此处理,我将如何创建图形对象?处理完成后,如何从我正在使用的 Graphics 对象中提取位图? 我一直无法找到如何执行此操作的好示例。
另外:格式化代码示例时,如何添加换行符? 如果有人能给我留言解释我真的很感激。 谢谢!
I'd like to use GDI+ to render an image on a background thread. I found this example on how to rotate an image using GDI+, which is the operation I'd like to do.
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();
}
My question has two parts:
How would you accomplish
this.CreateGraphics()
on a background thread? Is it possible? My understanding is that a UI object isthis
in this example. So if I'm doing this processing on a background thread, how would I create a graphics object?How would I then extract a bitmap from the Graphics object I'm using once I'm done processing? I haven't been able to find a good example of how to do that.
Also: when formatting a code sample, how do I add newlines? If someone could leave me a comment explaining that I'd really appreciate it. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要在位图上绘图,您不需要为 UI 控件创建
Graphics
对象。 您可以使用FromImage
方法为位图创建一个Graphics
对象:Graphics
对象不包含您向其绘制的图形,而是包含它只是在另一个画布(通常是屏幕)上绘图的工具,但它也可以是 Bitmap 对象。因此,您不是先绘制然后提取位图,而是先创建位图,然后创建
Graphics
对象来在其上绘制:To draw on a bitmap you don't want to create a
Graphics
object for an UI control. You create aGraphics
object for the bitmap using theFromImage
method:A
Graphics
object doesn't contain the graphics that you draw to it, instead it's just a tool to draw on another canvas, which is usually the screen, but it can also be aBitmap
object.So, you don't draw first and then extract the bitmap, you create the bitmap first, then create the
Graphics
object to draw on it: