获取矩形和线的交点 [英] Get intersection point of rectangle and line

查看:399
本文介绍了获取矩形和线的交点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到矩形和线条的交叉点。
我有内部矩形B点(矩形的中心),并有A点之外。我需要找到C点的矩形边框。
我也得到宽度和矩形的高度。

I need get intersection point of rectangle and line. I have point B inside rectangle(center of rectangle) and have point A outside. And i need to find point C on one of rectangle borders. Also I get width and height of rectangle.

这一切都将成为 WPF 应用程序,因此,如果在功能的任何版本,我会很高兴。

All this will be WPF application, so if any build in functions i will be very happy.

推荐答案

解决方案C#,WPF:

Solution for C#, WPF:

 /// <summary>
    /// Get Intersection point
    /// </summary>
    /// <param name="a1">a1 is line1 start</param>
    /// <param name="a2">a2 is line1 end</param>
    /// <param name="b1">b1 is line2 start</param>
    /// <param name="b2">b2 is line2 end</param>
    /// <returns></returns>
    public static Vector? Intersects(Vector a1, Vector a2, Vector b1, Vector b2)
    {
        Vector b = a2 - a1;
        Vector d = b2 - b1;
        var bDotDPerp = b.X * d.Y - b.Y * d.X;

        // if b dot d == 0, it means the lines are parallel so have infinite intersection points
        if (bDotDPerp == 0)
            return null;

        Vector c = b1 - a1;
        var t = (c.X * d.Y - c.Y * d.X) / bDotDPerp;
        if (t < 0 || t > 1)
            {
            return null;
        }

        var u = (c.X * b.Y - c.Y * b.X) / bDotDPerp;
        if (u < 0 || u > 1)
        {
            return null;
        }

        return a1 + t * b;
    }

修改
发现的链接以SO问题,其中上面的答案从何而来。

Edit Found Link to SO question where the answer above comes from.

这篇关于获取矩形和线的交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆