开发者

Cast Graphics to Image in C#

I have a pictureBox on a Windows Form.

I do the following to load a PNG file into it.

Bitmap bm = (Bitmap)Image.FromFile("Image.PNG", true);
Bitmap tmp;

public Form1() {
    InitializeComponent();
    this.tmp = new开发者_Python百科 Bitmap(bm.Width, bm.Height);
}

private void pictureBox1_Paint(object sender, PaintEventArgs e) {
    e.Graphics.DrawImage(this.bm, new Rectangle(0, 0, tmp.Width, tmp.Height), 0, 0, tmp.Width, tmp.Height, GraphicsUnit.Pixel);
}

However, I need to draw things on the image and then have the result displayed again. Drawing rectangles can only be done via the Graphics class.

I'd need to draw the needed rectangles on the image, make it an instance of the Image class again and save that to this.bm

I can add a button that executes this.pictureBox1.Refresh();, forcing the pictureBox to be painted again, but I can't cast Graphics to Image. Because of that, I can't save the edits to the this.bm bitmap.

That's my problem, and I see no way out.


What you need to do is use the Graphics.FromImage method, which will allow you to draw directly on the image instead of the temporary Graphics object create from within the Paint method:

using (Graphics g = Graphics.FromImage(this.bm))
{
    g.DrawRectangle(...);
}

Do this instead of (or in addition to) hooking the Paint method of the PictureBox. This way, you won't need to use a temporary image or Graphics object at all, and when you're finished modifying the original bitmap (this.bm) then you can invoke pictureBox1.Refresh to force the image to be re-displayed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜