Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - Get Canvas Color at Point

Let me first explain what I am trying to do. I am trying to create a Color picker Control like one of these on the right side: http://demos.telerik.com/silverlight/Themesgenerator/ However I want to create it myself for Learning.

At the moment I have made some sort of layout in xaml, and I use a Canvas with a LinearGradientBrush background. Now I am stuck while trying to decide which Color is at the specific Point. Is there any good way of finding this?.. I want to click at my canvas and get the ARGB of that specific Point. Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found the solution! Here it is if anyone need it!

[DllImport("gdi32")]
private static extern int GetPixel(int hdc, int nXPos, int nYPos);

[DllImport("user32")]
private static extern int GetWindowDC(int hwnd);

[DllImport("user32")]
private static extern int ReleaseDC(int hWnd, int hDC);

private static SolidColorBrush GetPixelColor(Point point)
{
    int lDC = GetWindowDC(0);
    int intColor = GetPixel(lDC, (int)point.X, (int)point.Y);

    // Release the DC after getting the Color.
    ReleaseDC(0, lDC);

    byte a = (byte)( ( intColor >> 0x18 ) & 0xffL );
    byte b = (byte)((intColor >> 0x10) & 0xffL);
    byte g = (byte)((intColor >> 8) & 0xffL);
    byte r = (byte)(intColor & 0xffL);
    Color color = Color.FromRgb(r, g, b);
    return new SolidColorBrush(color);
}

And I Call this method this way:

SolidColorBrush solidcolor = GetPixelColor(RightColorPanel.PointToScreen(point));

Color color = Color.FromArgb(solidcolor.Color.A,
                             solidcolor.Color.R,
                             solidcolor.Color.G,
                             solidcolor.Color.B);

LinearGradientBrush brush = new LinearGradientBrush();
brush.StartPoint = new Point(0, 0);
brush.EndPoint = new Point(1, 0);
brush.GradientStops.Add(new GradientStop(Colors.White, 0.0));
brush.GradientStops.Add(new GradientStop(color, 1));

MainColorPanel.Background = brush;

Where point is the Specific Point of my RightColorPanel that I keep my Colors at! This works realy great!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...