如何从最近的点找到路径上的点

本文关键字:路径 最近 | 更新日期: 2023-09-27 18:10:02

user128300有一个很好的解决方案获取路径或折线上最接近断开点的点但是我似乎不能正确地使用边距来定位点。

Xaml代码
<Style x:Key="Test_Path_Actual" TargetType="Path">
    <Setter Property="Stroke" Value="Blue"/>
    <Setter Property="StrokeThickness" Value="1"/>
    <Setter Property="StrokeLineJoin" Value="Round"/>
    <Setter Property="Stretch" Value="Fill"/>
    <Setter Property="Data" Value="M 0,20 L 30 0 L 60,20 L 30,40 Z"/>
</Style>
<Style TargetType="{x:Type c:ConnectorStrip}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type c:ConnectorStrip}">
                <Grid x:Name="PART_Grid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                    <Path x:Name="PART_PathActual" Style="{StaticResource Test_Path_Actual}"/>
                    <Path x:Name="PART_PathHitArea" Style="{StaticResource Test_Path_Hit_Area}"/>
                    <s:ConnectorSeeker x:Name="PART_ConnectorSeeker" Visibility="collapsed"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

c#代码
    void hitPath_MouseEnter(object sender, MouseEventArgs e)
    {
        ScaleX = this.DesiredSize.Width / origWidth;
        ScaleY = this.DesiredSize.Height / origHeight;
        ConnectorSeeker connSeekerL = GetConnectorSeeker();
        Point pt = GetClosestPointOnPath(e.GetPosition(this), actualPath.Data);
        if (connSeekerL != null)
        {
            double marginLeft = pt.X - (connSeekerL.Width / 2);
            double marginTop = pt.Y - (connSeekerL.Height / 2);
            double marginRight = this.DesiredSize.Width - pt.X - (connSeekerL.Width / 2);
            double marginBottom = this.DesiredSize.Height - pt.Y - (connSeekerL.Height / 2);
            connSeekerL.Margin = new Thickness(marginLeft, marginTop, marginRight, marginBottom);
            connSeekerL.Visibility = System.Windows.Visibility.Visible;
        }
        else
        {
            throw new Exception("Cannot find connector seeker");
        }
    }

当为当前光标位置使用e.t getposition (this)时,边距定位逻辑工作良好,但我希望该点位于最近的路径上

如何从最近的点找到路径上的点

明白了!

this.DesiredSize.Width替换为this.ActualWidth,将this.DesiredSize.Height替换为this.ActualHeight

原因是如果你的Path对象(或你的Path对象的容器)比父对象小,this.DesiredSize将小于实际大小,这将导致margin定位问题