WriteAbleBitmap.Pixels[] returns the wrong color (offset?)

220 views Asked by At

I'm trying to get the pixel color of a specific position (Tap event).

I have the following code:

 private void iiiimage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        Point point = e.GetPosition(iiiimage);

        ApplicationTitle.Text = point.ToString();

        var wb = new WriteableBitmap(iiiimage, null);


        int arrayPos = (int)point.X * (int)point.Y;

        PageTitle.Text = arrayPos.ToString();

        int colorAsInt = wb.Pixels[arrayPos];


        Color c = Color.FromArgb((byte)((colorAsInt >> 0x18) & 0xff),
                          (byte)((colorAsInt >> 0x10) & 0xff),
                          (byte)((colorAsInt >> 8) & 0xff),
                         (byte)(colorAsInt & 0xff));

        r3ct.Fill = new SolidColorBrush(c);

    }

The screenshot show what wrong. The position of the white error (the tip) is blue, but the code returns a pixel that is somewhere at the top of the image (red).

enter image description here

What am I doing wrong?

Kind regards, Niels

1

There are 1 answers

1
Jigsore On BEST ANSWER

Try doing the following modifications. I have no idea if this works on WP7, though. I guess ActualWidth and ActualHeight should be considered, since you need to translate coordinates expressed in units to pixels.

private void iiiimage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
    Point point = e.GetPosition(iiiimage);

    ApplicationTitle.Text = point.ToString();

    var wb = new WriteableBitmap(iiiimage, null);

    int x, y;
    x = (int)(wb.PixelWidth * point.X / iiiimage.ActualWidth);
    y = (int)(wb.PixelHeight * point.Y / iiiimage.ActualHeight);
    int arrayPos = y * wb.PixelWidth + x;

    PageTitle.Text = String.Format("({0} ; {1}) --> {2}", x, y, arrayPos);

    int colorAsInt = wb.Pixels[arrayPos];


    Color c = Color.FromArgb((byte)((colorAsInt >> 0x18) & 0xff),
                        (byte)((colorAsInt >> 0x10) & 0xff),
                        (byte)((colorAsInt >> 8) & 0xff),
                        (byte)(colorAsInt & 0xff));

    r3ct.Fill = new SolidColorBrush(c);
}