【问题标题】:How to find point on Path from the closest point?如何从最近的点找到路径上的点?
【发布时间】:2015-08-26 08:08:06
【问题描述】:

user128300 对此有一个很好的解决方案 Get point on a path or polyline which is closest to a disconnected point 但在使用边距定位点时,我似乎无法正确定位。

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.GetPosition(this) 时,边距定位逻辑可以正常工作,但我希望该点位于最近的路径上。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    知道了!

    只需将this.DesiredSize.Width 替换为this.ActualWidth 并将this.DesiredSize.Height 替换为this.ActualHeight

    原因是如果您的 Path 对象(或 Path 对象的容器)小于父对象,this.DesiredSize 将小于实际大小,从而导致边距定位问题。

    【讨论】:

      猜你喜欢
      • 2015-02-03
      • 2014-07-21
      • 2015-03-17
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多