WPF ImageControl描边图片
1 [TemplatePart(Name = "PART_Highlight", Type = typeof(Image))] 2 public class ImageControl : Control 3 { 4 Image HighLightImage = null; 5 6 public bool IsHighLight 7 { 8 get { return (bool)GetValue(IsHighLightProperty); } 9 set { SetValue(IsHighLightProperty, value); } 10 } 11 12 public static readonly DependencyProperty IsHighLightProperty = 13 DependencyProperty.Register("IsHighLight", typeof(bool), typeof(ImageControl), new FrameworkPropertyMetadata(false, propertyChangedCallback: OnIsHighLightChanged)); 14 15 private static void OnIsHighLightChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 16 { 17 var ic = d as ImageControl; 18 if((bool)e.NewValue) 19 { 20 ic.HighLightImage.Visibility = Visibility.Visible; 21 string path = ic.Source.ToString().Replace("file:///", string.Empty); 22 byte[] bs = null; 23 using (var bitmap = new System.Drawing.Bitmap(path)) 24 bs = bitmap.GetVerge1(true); 25 WriteableBitmap wb = new WriteableBitmap((int)ic.Source.Width + 2, (int)ic.Source.Height + 2, 96, 96, PixelFormats.Bgra32, null); 26 wb.Lock(); 27 wb.WritePixels(new Int32Rect(0, 0, wb.PixelWidth, wb.PixelHeight), bs, wb.PixelWidth * 4, 0); 28 wb.Unlock(); 29 ic.HighLightImage.Source = wb; 30 } 31 else 32 { 33 ic.HighLightImage.Source = null; 34 } 35 } 36 37 public ImageSource Source 38 { 39 get { return (ImageSource)GetValue(SourceProperty); } 40 set { SetValue(SourceProperty, value); } 41 } 42 43 public static readonly DependencyProperty SourceProperty = 44 DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImageControl), new FrameworkPropertyMetadata((ImageSource)null)); 45 46 public override void OnApplyTemplate() 47 { 48 base.OnApplyTemplate(); 49 HighLightImage = GetTemplateChild("PART_Highlight") as Image; 50 } 51 52 protected override void OnMouseEnter(MouseEventArgs e) 53 { 54 IsHighLight = true; 55 base.OnMouseEnter(e); 56 } 57 58 protected override void OnMouseLeave(MouseEventArgs e) 59 { 60 IsHighLight = false; 61 base.OnMouseLeave(e); 62 } 63 }
样式:
<Style TargetType="local:ImageControl"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="local:ImageControl"> <Canvas> <Image Source="{TemplateBinding Source}"/> <Image Name="PART_Highlight" IsHitTestVisible="False" Canvas.Left="-1" Canvas.Top="-1"/> </Canvas> </ControlTemplate> </Setter.Value> </Setter> </Style>
使用:
<local:ImageControl x:Name="img" Source="D:\1.png" />