Search code examples
c#wpfcolorscanvasmouse

Canvas background for retrieving color


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...


Solution

  • 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