Maximilian
Maximilian

Reputation: 37

GDI :Figure out which color the pixel has, which I drew before

I am trying to figure out which color the Pixel has which I drew before in red.

So as I read its not possible to do that directly, transformed my Graphics object to a Bitmap, which has the function GetPIxel and same width/height as my graphics object. Otherwise i think it would not function.

But it always returns me: Color [A=0, R=0, G=0, B=0]

Which i guess means White.

Here is my Code:

namespace GDi
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.components = new System.ComponentModel.Container();
            this.Size = new System.Drawing.Size(400, 400);
            this.Text = "Display At Startup";
            this.BackColor = Color.White;
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            Graphics dc = this.CreateGraphics();
            this.Show();
            Pen BluePen = new Pen(Color.Blue, 3);
            dc.DrawRectangle(BluePen, 0, 0, 50, 50);
            Pen RedPen = new Pen(Color.Red, 2);

            dc.DrawEllipse(RedPen, 20, 70, 80, 0);
            dc.DrawEllipse(RedPen, 2, 88, 300, 0);
            Bitmap myBitmap = new Bitmap(400, 400, dc);
            string test = myBitmap.GetPixel(2, 88).ToString();
            MessageBox.Show(test);
        }
    }
}

Any idea why it doesent works?

Upvotes: 1

Views: 75

Answers (1)

IMil
IMil

Reputation: 1400

It doesn't work because the Bitmap constructor simply creates a new empty bitmap with no relation to your previous drawing.

You should probably use a different approach:

  1. Create a Bitmap object like you've done
  2. Create a Graphics object to draw in this bitmap using Graphics.FromImage method
  3. Draw into this new Graphics
  4. When needed, read the pixel color you need from your bitmap
  5. When the drawing is done, copy the bitmap to the form
  6. Dispose your new Graphics and Bitmap objects. Alternatively, you may hold the Bitmap for a long time, but Graphics should better be created on each redraw.

Upvotes: 1

Related Questions