某些时候,需要验证控件之间是否存在重叠的情况,可以借助 System.Windows.Rect.IntersectsWith 来验证;如果需要获取重叠的部分,则使用 System.Windows.Rect.Intersect 来实现!
<Window x:Class="轨迹规划Demo.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:轨迹规划Demo" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <Canvas x:Name="can"> <Border x:Name="b1" BorderThickness="1" BorderBrush="Red" Canvas.Left="10" Canvas.Top="10" Width="200" Height="200" /> <Border x:Name="b2" BorderThickness="1" BorderBrush="Black" Canvas.Left="50" Canvas.Top="40" Width="200" Height="200" /> </Canvas> <StackPanel HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="10" > <Button Content="计算交集" Click="Button_Click"/> </StackPanel> </Grid> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace 轨迹规划Demo { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { System.Windows.Rect r1 = new Rect((double)b1.GetValue(Canvas.LeftProperty), (double)b1.GetValue(Canvas.TopProperty), b1.ActualWidth, b1.ActualHeight); System.Windows.Rect r2 = new Rect((double)b2.GetValue(Canvas.LeftProperty), (double)b2.GetValue(Canvas.TopProperty), b2.ActualWidth, b2.ActualHeight); r1.Intersect(r2); //r1.IntersectsWith(r2); Border b = new Border(); b.Background = new SolidColorBrush(Colors.Blue); b.Width = r1.Width; b.Height = r1.Height; b.SetValue(Canvas.LeftProperty, r1.X); b.SetValue(Canvas.TopProperty, r1.Y); can.Children.Add(b); } } }