基于WPF自定義實(shí)現(xiàn)一個(gè)顏色拾取器
1.界面布局
<GroupBox
Padding="0"
BorderThickness="0.1"
Foreground="White"
Header="Color Pick">
<DockPanel>
<GroupBox
Margin="5,0,5,2"
BorderThickness="0.1"
DockPanel.Dock="Right"
Foreground="White"
Header="Color">
<WrapPanel
Width="200"
DockPanel.Dock="Right"
Orientation="Vertical">
<WrapPanel Margin="5,5,0,0">
<Label
VerticalContentAlignment="Center"
Content="R:"
Foreground="White" />
<Label
Name="Label_R"
Margin="5,0,0,0"
VerticalContentAlignment="Center"
Content="0"
Foreground="White" />
</WrapPanel>
<WrapPanel Margin="5,5,0,0">
<Label
VerticalContentAlignment="Center"
Content="G:"
Foreground="White" />
<Label
Name="Label_G"
Margin="5,0,0,0"
VerticalContentAlignment="Center"
Content="0"
Foreground="White" />
</WrapPanel>
<WrapPanel Margin="5,5,0,0">
<Label
VerticalContentAlignment="Center"
Content="B:"
Foreground="White" />
<Label
Name="Label_B"
Margin="5,0,0,0"
VerticalContentAlignment="Center"
Content="0"
Foreground="White" />
</WrapPanel>
<WrapPanel Background="Black">
<Image
x:Name="Image_Clolor"
Width="200"
Height="150"
Margin="0" />
</WrapPanel>
</WrapPanel>
</GroupBox>
<GroupBox
Name="WrapPanel_Image"
Padding="0,0,0,0"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
Background="Black"
BorderThickness="0"
ClipToBounds="True"
Cursor="Cross"
DockPanel.Dock="Left">
<Image
x:Name="Image_Img"
Width="{Binding ElementName=WrapPanel_Image, Path=ActualWidth}"
Height="{Binding ElementName=WrapPanel_Image, Path=ActualHeight}"
Margin="-5,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
ClipToBounds="True"
MouseWheel="Image_Img_MouseWheel"
PreviewMouseLeftButtonDown="Image_Img_PreviewMouseLeftButtonDown"
PreviewMouseLeftButtonUp="Image_Img_PreviewMouseLeftButtonUp"
PreviewMouseMove="Image_Img_PreviewMouseMove"
PreviewMouseRightButtonDown="Image_Img_PreviewMouseRightButtonDown"
RenderOptions.BitmapScalingMode="Fant"
Stretch="Uniform">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="Image_Img_ScaleTransform" CenterX="0" CenterY="0" ScaleX="1" ScaleY="1" />
<TranslateTransform x:Name="Image_Img_TranslateTransform" X="0" Y="0" />
</TransformGroup>
</Image.RenderTransform>
</Image>
</GroupBox>
</DockPanel>
</GroupBox>
2.后臺實(shí)現(xiàn)
/// <summary>
/// ColorPickerUserControl.xaml 的交互邏輯
/// </summary>
public partial class ColorPickerUserControl : UserControl
{
//圖像原圖
private Bitmap originalBitmap;
//縮放比率
private double ScaleRatio = 0.2;
//鼠標(biāo)按下坐標(biāo)
private System.Windows.Point currentClickPoint = new System.Windows.Point(0, 0);
//鼠標(biāo)按下標(biāo)識
bool isImageLeftButtonDown = false;
/// <summary>
/// 當(dāng)前選中顏色
/// </summary>
public System.Drawing.Color CurrentColor;
public ColorPickerUserControl()
{
InitializeComponent();
}
/// <summary>
/// 資源釋放
/// </summary>
public void Dispose()
{
try
{
Image_Img.Source?.Freeze();
Image_Img.Source = null;
originalBitmap?.Dispose();
originalBitmap = null;
Image_Clolor.Source?.Freeze();
Image_Clolor.Source = null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 加載圖像
/// </summary>
/// <param name="fileName">圖像文件路徑</param>
public void InitImage(string fileName)
{
try
{
Image_Img.Stretch = Stretch.Uniform;
if (File.Exists(fileName))
{
Task<BitmapImage> task = Task.Run(() =>
{
//后臺讀取圖像,防止圖像太大卡住主線程
using (var stream = File.OpenRead(fileName))
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = stream;
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
bmp.Freeze(); // 凍結(jié)對象以便跨線程訪問
originalBitmap = new Bitmap(stream);
return bmp;
}
});
task.Wait();
Image_Img.Source = task.Result;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 加載圖像
/// </summary>
/// <param name="bitmap">圖像</param>
public void InitImage(Bitmap bitmap)
{
try
{
originalBitmap?.Dispose();
originalBitmap = null;
originalBitmap = new Bitmap(bitmap);
// 將Bitmap轉(zhuǎn)換為WPF的BitmapImage
BitmapImage bitmapImage;
using (MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
memory.Position = 0;
bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
}
Image_Img.Source = bitmapImage;
bitmapImage?.Freeze();
bitmapImage = null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 鼠標(biāo)左鍵按下
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Image_Img_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
try
{
if (e.ChangedButton != MouseButton.Left) return;
var pos = e.GetPosition((System.Windows.Controls.Image)e.Source);
currentClickPoint = pos;
isImageLeftButtonDown = true;
var img = ((System.Windows.Controls.Image)e.Source).Source as BitmapSource;
ColorPicker(img, pos);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 圖像點(diǎn)轉(zhuǎn)真實(shí)點(diǎn)
/// </summary>
/// <param name="thumbnailX"></param>
/// <returns></returns>
private double ToCamRealX(double thumbnailX)
{
return (thumbnailX / Image_Img.ActualWidth) * (double)(originalBitmap?.Width ?? 0);
}
/// <summary>
/// 圖像點(diǎn)轉(zhuǎn)真實(shí)點(diǎn)
/// </summary>
/// <param name="thumbnailY"></param>
/// <returns></returns>
private double ToCamRealY(double thumbnailY)
{
return (thumbnailY / Image_Img.ActualHeight) * (double)(originalBitmap?.Height ?? 0);
}
/// <summary>
/// 顏色拾取
/// </summary>
/// <param name="img"></param>
/// <param name="pos"></param>
/// <exception cref="Exception"></exception>
protected void ColorPicker(BitmapSource img, System.Windows.Point pos)
{
try
{
int stride = img.PixelWidth * 4;
int size = img.PixelHeight * stride;
byte[] pixels = new byte[(int)size];
img.CopyPixels(pixels, stride, 0);
// Get pixel
//屏幕坐標(biāo)轉(zhuǎn)圖像坐標(biāo)
var x = (int)ToCamRealX(pos.X);
var y = (int)ToCamRealY(pos.Y);
int index = y * stride + 4 * x;
byte red = pixels[index];
byte green = pixels[index + 1];
byte blue = pixels[index + 2];
byte alpha = pixels[index + 3];
System.Drawing.Color color = System.Drawing.Color.FromArgb(alpha, blue, green, red);
Label_R.Content = color.R.ToString();
Label_G.Content = color.G.ToString();
Label_B.Content = color.B.ToString();
//string ColorText = "#" + color.A.ToString("X2") + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
ColorShow(color);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 顏色顯示
/// </summary>
/// <param name="color"></param>
/// <exception cref="Exception"></exception>
private void ColorShow(System.Drawing.Color color)
{
try
{
CurrentColor = color;
int w = (int)Image_Clolor.Width;
int h = (int)Image_Clolor.Height;
Bitmap bitmap = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
for (int x = 0; x < w; x++)
{
for (int y = 0; y < h; y++)
{
bitmap.SetPixel(x, y, color);
}
}
BitmapImage bitmapImage;
using (MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
memory.Position = 0;
bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
}
Image_Clolor.Source = bitmapImage;
bitmapImage?.Freeze();
bitmapImage = null;
bitmap.Dispose();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 鼠標(biāo)滾動(dòng)縮放
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Image_Img_MouseWheel(object sender, MouseWheelEventArgs e)
{
try
{
System.Windows.Point center = e.GetPosition(Image_Img);
double scale = 0;
if (e.Delta > 0)
{
scale = Image_Img_ScaleTransform.ScaleX + ScaleRatio;
if (scale > 30)
{
return;
}
}
else
{
scale = Image_Img_ScaleTransform.ScaleX - ScaleRatio;
if (scale < 0.5)
{
return;
}
}
//圖像
Image_Img_ScaleTransform.ScaleX = scale;
Image_Img_ScaleTransform.ScaleY = scale;
}
catch
{
}
}
/// <summary>
/// 鼠標(biāo)移動(dòng)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Image_Img_PreviewMouseMove(object sender, MouseEventArgs e)
{
try
{
if (isImageLeftButtonDown == true)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
//移動(dòng)
System.Windows.Point newPoint = e.GetPosition(Image_Img);
double deltaX = newPoint.X - currentClickPoint.X;
double deltaY = newPoint.Y - currentClickPoint.Y;
//圖像
Image_Img_TranslateTransform.X += deltaX;
Image_Img_TranslateTransform.Y += deltaY;
}
}
}
catch
{
}
}
/// <summary>
/// 鼠標(biāo)放開
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Image_Img_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
isImageLeftButtonDown = false;
}
/// <summary>
/// 鼠標(biāo)右鍵
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Image_Img_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
Recombination();
}
/// <summary>
/// 重置圖像大小
/// </summary>
private void Recombination()
{
try
{
//圖像
Image_Img_ScaleTransform.ScaleX = 1;
Image_Img_ScaleTransform.ScaleY = 1;
Image_Img_TranslateTransform.X = 0;
Image_Img_TranslateTransform.Y = 0;
}
catch
{
}
}
}
3.效果

到此這篇關(guān)于基于WPF自定義實(shí)現(xiàn)一個(gè)顏色拾取器的文章就介紹到這了,更多相關(guān)WPF顏色拾取器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#判斷一個(gè)字符串是否包含另一個(gè)字符串的方法
這篇文章主要介紹了C#判斷一個(gè)字符串是否包含另一個(gè)字符串的方法,涉及C#中IndexOf方法的使用技巧,非常簡單實(shí)用,需要的朋友可以參考下2015-04-04
C#連續(xù)任務(wù)Task.ContinueWith方法
這篇文章介紹了C#中的連續(xù)任務(wù)Task.ContinueWith方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04
C#實(shí)現(xiàn)給Word每一頁設(shè)置不同圖片水印
Word中設(shè)置水印時(shí),可加載圖片設(shè)置為水印效果,但通常添加水印效果時(shí),會對所有頁面都設(shè)置成統(tǒng)一效果。本文將利用C#實(shí)現(xiàn)給Word每一頁設(shè)置不同圖片水印的效果,需要的可以參考一下2022-02-02
unity實(shí)現(xiàn)虛擬搖桿控制Virtual Joystick
這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)虛擬搖桿控制Virtual Joystick,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
C# DataGridView中實(shí)現(xiàn)勾選存儲數(shù)據(jù)和右鍵刪除數(shù)據(jù)(示例代碼)
這篇文章主要介紹了C# DataGridView中實(shí)現(xiàn)勾選存儲數(shù)據(jù)和右鍵刪除數(shù)據(jù)的示例代碼,通過示例代碼給大家展示運(yùn)行效果圖,需要的朋友可以參考下2021-07-07

