views:

213

answers:

1

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

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 then I can to 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 is it any other solution.

+2  A: 

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.

Adam Robinson
Thanks! Keep tracking of the maximum X and Y values that get used as draw will work for me.
StreamT
I'm assuming that clipping off of the left or the top isn't going to happen?
Jacob G
@Jacob: That was my assumption, but either pattern could be fairly easily adapted to account for that as well.
Adam Robinson