2010年3月15日 星期一

在WPF中取得像素顏色(Pick Color)

在寫調色盤介面的時候,需要在一張圖透過滑鼠去選取顏色

一個很簡單的做法就是使用一個Image控制項,加上MouseDown事件
另外加一個色塊去表示取出的顏色

<StackPanel>
<!-- an image to pick color from -->
<Image Name="img" Source="color.png"
MouseDown="Image_MouseDown" />
<!-- an rectangle to output picked color -->
<Rectangle Name="rec" Height="20" />
</StackPanel>

然後將MouseDown的事件處理定義如下

private void Image_MouseDown(
object sender, MouseButtonEventArgs e)
{
/// get a bitmap reference
BitmapSource bmp = img.Source as BitmapSource;

/// get mouse down position
Point pos = e.GetPosition(img);

/// map position to pixel base
int x = (int)((pos.X / img.ActualWidth) *
bmp.PixelWidth);
int y = (int)((pos.Y / img.ActualHeight) *
bmp.PixelHeight);

/// pick the color to a byte array
CroppedBitmap cb = new CroppedBitmap(
bmp, new Int32Rect(x, y, 1, 1));
byte[] pix = new byte[4];
cb.CopyPixels(pix, 4, 0);

/// show the picked color
rec.Fill = new SolidColorBrush(
Color.FromRgb(pix[2], pix[1], pix[0]));
}

這樣在程式中點那張圖的時候
下方的長方形圖快就會被填滿為點下選取到的顏色

注意這邊我們對應到圖片的位置的時候
要轉換成PixelWidth & PixelHeight
因為圖片本身的dpi可能不同
直接使用圖片的大小可能會對應錯誤或超出範圍

--
參考資料
WPF : A Simple Color Picker With Preview
BitmapSource.CopyPixels 方法 (Array, Int32, Int32)

沒有留言:

張貼留言