驗證控件是否重疊,獲取重疊部分

某些時候,需要驗證控件之間是否存在重疊的情況,可以藉助  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);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章