欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

WPF 命中测试HitTest

发布时间:2023/12/4 50 豆豆
生活随笔 收集整理的这篇文章主要介绍了 WPF 命中测试HitTest 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

获取不规则图片的点击事件,

如果一个Canvas中,有很多图形,比如下图:矩形,菱形等。

如果每个图形都加一个点击事件,想要一个通用的方法,获取鼠标点击在了哪个图形上,这里可以使用VisualTreeHelper.HitTest方法。

直接看看示例代码:

MainWindow.xaml:

<Window x:Class="wpfcore.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:wpfcore" xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"mc:Ignorable="d"Background="LightBlue"UseLayoutRounding="True"Title="MainWindow" Width="600" Height="340"><WrapPanel HorizontalAlignment="Center" VerticalAlignment="Center" Name="panel" MouseUp="mouseUp"><Path x:Name="矩形1" Margin="5" Fill="Red" Data="M0 0,100 0,100,100,0 100Z"/><Path x:Name="矩形2" Margin="-5" Fill="Green" Data="M0 0,100 0,100,100,0 100Z"><Path.RenderTransform><RotateTransform CenterX="50" CenterY="50" Angle="60"/></Path.RenderTransform></Path><Path x:Name="菱形1" Stroke="Red" Fill="Red"><Path.Data><PathGeometry><PathFigure IsClosed="True" StartPoint="50,0"><LineSegment Point="75,50"></LineSegment><LineSegment Point="50,100"></LineSegment><LineSegment Point="25,50"></LineSegment></PathFigure></PathGeometry></Path.Data></Path><Path x:Name="菱形2" Stroke="Red" Fill="Red"><Path.Data><PathGeometry><PathFigure IsClosed="True" StartPoint="50,0"><LineSegment Point="75,50"></LineSegment><LineSegment Point="50,100"></LineSegment><LineSegment Point="25,50"></LineSegment></PathFigure><PathGeometry.Transform><RotateTransform Angle="-115" CenterX="50" CenterY="100"></RotateTransform></PathGeometry.Transform></PathGeometry></Path.Data></Path></WrapPanel> </Window>

MainWindow.cs:

using System; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Input; using System.Windows.Media;namespace wpfcore {public partial class MainWindow : Window{public MainWindow(){InitializeComponent();DataContext = this;}private void mouseUp(object sender, MouseButtonEventArgs e){var p = e.GetPosition(sender as UIElement);VisualTreeHelper.HitTest(panel, null, callback, new PointHitTestParameters(p));System.Diagnostics.Debug.WriteLine($"------------------------");}private HitTestResultBehavior callback(HitTestResult result){System.Diagnostics.Debug.WriteLine($"点击了{result.VisualHit.GetValue(NameProperty)}");return HitTestResultBehavior.Continue;}} }

输出点击点在哪个图形内,当然,你也可以做别的事。

如果喜欢,点个赞呗~

总结

以上是生活随笔为你收集整理的WPF 命中测试HitTest的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。