在上一篇文章中,已经把绘制的色轮,显示在Image控件中了。
但光显示没什么意义,还需要实现的一个功能是:鼠标在Image控件中点一下,就能取出点击位置的颜色。
这里最核心的一个问题是,屏幕上(Image控件)的坐标系,与ImageSource这张图篇的坐标系的对应关系。
因为控件是可以大,可以小的。那么如何确定鼠标在Image控件上的点,对应到ImageSource图片上的点呢?
这里可以采用比例的方式。在Image控件的MouseDown事件中:
// Source为生成的WriteableBitmap对象
private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
if (image == null) return;
Point mouse = e.GetPosition(image);
int x = (int)(image.Source.Width / image.ActualWidth * mouse.X);
int y = (int)(image.Source.Height / image.ActualHeight * mouse.Y);
unsafe
{
WriteableBitmap source = Source;
source.Lock();
IntPtr pointer = source.BackBuffer;
int offset = (x + y * Source.PixelWidth) * source.Format.BitsPerPixel / 8;
Blue = Marshal.ReadByte(pointer, offset);
Green = Marshal.ReadByte(pointer, offset + 1);
Red = Marshal.ReadByte(pointer, offset + 2);
Alpha = Marshal.ReadByte(pointer, offset + 3);
source. Unlock);
}
}
mouse点是相对于Image控件的。通过等比换算,计算出鼠标点,在图片上的坐标。然后通过“可写的图片”,读取该坐标点的颜色值。