views:

121

answers:

2

Hi,

I have a canvas with a background set to be lineargradientbrush....how do I then extract the color from this background at a particular mouse point (x,y)?

I can do this with a BitmappedImage fine...as this deals with pixels, not sure about a canvas though...

Thanks greatly in advance,

U.

A: 

On Microsoft Support, there is this article about finding the color of the pixel at the mouse cursor:

http://support.microsoft.com/kb/892462

JYelton
That article is for WinForms
Henk Holterman
A: 

WPF is vector based so it doesn't really have any concept of a "pixel" except within a bitmap data structure. However you can determine the average color of a rectangular area, including a 1x1 rectangular area (which generally comes out as a single pixel on the physical screen).

Here's how to do this:

public Color GetPixelColor(Visual visual, int x, int y)
{
  return GetAverageColor(visual, new Rect(x,y,1,1));
}

public Color GetAverageColor(Visual visual, Rect area)
{
  var bitmap = new RenderTargetBitmap(1,1,96,96,PixelFormats.Pbgra32);
  bitmap.Render(
   new Rectangle
    {
      Width = 1, Height = 1,
      Fill = new VisualBrush { Visual = visual, Viewbox = area }
    });
  var bytes = new byte[4];
  bitmap.CopyPixels(bytes, 1, 0);
  return Color.FromArgb(bytes[0], bytes[1], bytes[2], bytes[3]);
}

Here is how you would use it:

Color pixelColor = GetPixelColor(canvas, x, y);

The way this code works is:

  1. It fills a 1x1 Rectangle using a VisualBrush that shows the selected area of the canvas
  2. It renders this Rectangle on to a 1-pixel bitmap
  3. It gets the pixel color from the rendered bitmap
Ray Burns
I tried using your code, but I get a System.ArgumentOutOfRangeException: Sth like: "Parameter value can not be less than 4" at bitmap.CopyPixels(bytes, 1, 0). My params are x=57, y=78.Using bitmap.CopyPixels(bytes, 4, 0) works, however, then "bytes" only holds "0"s, which will always give a transparent black.
Torsten