adam
adam

Reputation: 179

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.

Upvotes: 0

Views: 384

Answers (4)

AustrianHunter
AustrianHunter

Reputation: 9

You could write a new Class, for example:

class ColorRectangles
{
    public Color color;
    public Rectangle[] rects;

    public ColorRectangle(Rectangle[] rects, Color color) : base(x, y, width, height)
    {
        this.color = color
        this.rects = rects;
    }
}

and then set the Rectangles Color with g.FillRectangles(new SolidBrush(Rectangle.color), Rectangle.rects);

Upvotes: 0

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

The FillRectangles draws the rectangles with the brush (color) you passed. There is no reference from any rectangle to any color. It just executes a drawing command to a Graphics object.

A Rectangle doesn't have a color. So, nope, you cannot. If you explain why you would need it, there might be other solutions to get the desired results.

Upvotes: 1

Flater
Flater

Reputation: 13773

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.

Upvotes: 0

Siavash
Siavash

Reputation: 3009

You can find the position of center pixel of your rectangle, then you can use GetPixel method to get information about such as color.

   Color pixelColor = myBitmap.GetPixel(50, 50);

Upvotes: 3

Related Questions