简体   繁体   中英

How can I get a convert a Graphics object to a Bitmap (or access it as a Bitmap)

I know the whole

Bitmap bmp = new Bitmap(100,100) ;
Graphics graphics = Graphics.FromImage(bmp) ;

But that is not what I need to do. Essentially what I am trying to do is slightly modify how something is draw on the screen (it is a rectangle with a line in the middle). I need to change the background of the rectangle (which I could do with a pixel comparison or other similar method).

If I could somehow turn it into a bitmap. There is no way (that I can tell to get/set/modify) the graphics object on the pixel level.

Bob Powell has written an excellent article about accessing image bits directly.

https://web.archive.org/web/20141229164101/http://bobpowell.net/lockingbits.aspx

You could do this using a for loop like so:

for(int i = 0; i < bmp.Width; i++)
{
    for(int j = 0; j < bmp.Height; j++)
    {
        var pixel = bmp.GetPixel(i, j);
        //do stuff with pixel here :)
    }
}

EDIT: After seeing Tilak's comment, if performance is an issue for you then he is right! (Thanks, I did not know about LockBits! +1) Some examples can be found on the MS BitmapData Class page . However, if this seems complicated the above method should do the trick :)

使用图形后,只需保存位图 - 对图形所做的更改都会对位图进行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM