Search code examples
c#.netrectanglesgetcolor

Get Rectangle's color after FillRectangles


How can I get the color of a Rectangle after creating it?

I'm using this code to create them :

SolidBrush sb = new SolidBrush(Color.Red);
Graphics g = panel1.CreateGraphics();
Rectangle[] rects = { new Rectangle(0, 0, 15, 15), new Rectangle(16, 16, 15, 15), new Rectangle(16, 0, 15, 15), new Rectangle(0, 16, 15, 15) };
g.FillRectangles(sb,rects);

And now I want to get the color of the 3rd rectangle rects[2] = ....

Is it possible to get this? And it should return Color.Red.


Solution

  • If you store the image, you only store the result (i.e. the grid of pixels). There is no information on how you created this image.

    E.g. based on the bitmap image alone, you cannot differentiate between two adjacent squares (new Rectangle(0, 0, 15, 15), new Rectangle(15, 0, 15, 15) and a single rectangle that has twice the width (new Rectangle(0, 0, 30, 15)).

    So the short answer to your question is no, you cannot do that.

    Unless you store your information (the rectangles you drew) separately and then use that to find the appropriate pixel on the image (and this only works in simple cases - if you overlapped an earlier rectangle, it's going to be impossible)

    But if you're going to store the rectangle information anyway, you might as well store its color and then you don't need to reverse engineer the image anymore. So the answer remains that you cannot do this based on an image alone.