简体   繁体   中英

C# Graphics class: get size of drawn content

I am writing to a Graphics object dynamically and don't know the actual size of the final image until all output is passed.

So, I create a large image and create Graphics object from it:

int iWidth = 600;
int iHeight = 2000;

bmpImage = new Bitmap(iWidth, iHeight);            
graphics = Graphics.FromImage(bmpImage);
graphics.Clear(Color.White);        

How can I find the actual size of written content, so I will be able to create a new bitmap with this size and copy the content to it.

It is really hard to calculate the content size before drawing it and want to know if there is any other solution.

The best solution is probably to keep track of the maximum X and Y values that get used as you draw, though this will be an entirely manual process.

Another option would be to scan full rows and columns of the bitmap (starting from the right and the bottom) until you encounter a non-white pixel, but this will be a very inefficient process.

int width = 0;
int height = 0;

for(int x = bmpImage.Width - 1, x >= 0, x++)
{
    bool foundNonWhite = false;

    width = x + 1;

    for(int y = 0; y < bmpImage.Height; y++)
    {
        if(bmpImage.GetPixel(x, y) != Color.White)
        {
            foundNonWhite = true;
            break;
        }
    }

    if(foundNonWhite) break;
}

for(int y = bmpImage.Height - 1, x >= 0, x++)
{
    bool foundNonWhite = false;

    height = y + 1;

    for(int x = 0; x < bmpImage.Width; x++)
    {
        if(bmpImage.GetPixel(x, y) != Color.White)
        {
            foundNonWhite = true;
            break;
        }
    }

    if(foundNonWhite) break;
}

Again, I don't recommend this as a solution , but it will do what you want without your having to keep track of the coordinate space that you actually use.

Just check the value of these properties

float width = graphics.VisibleClipBounds.Width;
float height = graphics.VisibleClipBounds.Height;

A RectangleF structure that represents a bounding rectangle for the visible clipping region of this Graphics.

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