原文:
Png图片的透明部分穿透测试
private void Window_MouseMove(object sender, MouseEventArgs e)
{
NavBtnList.Clear(); Point mouseP = e.GetPosition(this); VisualTreeHelper.HitTest(this, new HitTestFilterCallback(HitFilter), new HitTestResultCallback(HitResult), new PointHitTestParameters(mouseP)); if (NavBtnList.Count > 0) { for (int k = 0; k < NavBtnList.Count; k++) { IconBtn element = NavBtnList[k] as IconBtn; DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext context = drawingVisual.RenderOpen()) { VisualBrush brush = new VisualBrush(element) { Stretch = Stretch.None }; context.DrawRectangle(brush, null, new Rect(0, 0, element.ActualWidth, element.ActualHeight)); context.Close(); } //dpi可以自己设定 // 获取dpi方法:PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice RenderTargetBitmap bitmap = new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 96, 96, PixelFormats.Pbgra32); bitmap.Render(drawingVisual); Point p = this.TranslatePoint(mouseP, element); //全局坐标转为局部坐标point //获取鼠标下像素颜色值 var c = getImagePointColor((bitmap as BitmapSource), (int)p.X, (int)p.Y); if (c != Convert16ToColor("#00000000")) { if (element.IsEnabled) { } break; } bitmap.Clear(); }
}
1 //鼠标按下获得所有IconBtnFrame 存储在NavBtnList里 2 List<IconBtn> NavBtnList = new List<IconBtn>(); 3 4 public HitTestFilterBehavior HitFilter(DependencyObject dObject) 5 { 6 if (dObject is IconBtn) 7 { 8 NavBtnList.Add(dObject as IconBtn); 9 } 10 return HitTestFilterBehavior.Continue; 11 } 12 13 public HitTestResultBehavior HitResult(HitTestResult result) 14 { 15 return HitTestResultBehavior.Continue; 16 }