为了账号安全,请及时绑定邮箱和手机立即绑定

快速矩形到矩形的交点

快速矩形到矩形的交点

明月笑刀无情 2019-12-25 14:35:31
测试2个矩形是否相交的快速方法是什么?在Internet上进行了搜索,找到了这种单行代码(WOOT!),但我不知道如何用Javascript编写它,它似乎是用C ++的古老形式编写的。struct{    LONG    left;    LONG    top;    LONG    right;    LONG    bottom;} RECT; bool IntersectRect(const RECT * r1, const RECT * r2){    return ! ( r2->left > r1->right        || r2->right < r1->left        || r2->top > r1->bottom        || r2->bottom < r1->top        );}
查看完整描述

3 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

.NET Framework就是这样实现Rectangle.Intersect


public bool IntersectsWith(Rectangle rect)

{

  if (rect.X < this.X + this.Width && this.X < rect.X + rect.Width && rect.Y < this.Y + this.Height)

    return this.Y < rect.Y + rect.Height;

  else

    return false;

}

或静态版本:


public static Rectangle Intersect(Rectangle a, Rectangle b)

{

  int x = Math.Max(a.X, b.X);

  int num1 = Math.Min(a.X + a.Width, b.X + b.Width);

  int y = Math.Max(a.Y, b.Y);

  int num2 = Math.Min(a.Y + a.Height, b.Y + b.Height);

  if (num1 >= x && num2 >= y)

    return new Rectangle(x, y, num1 - x, num2 - y);

  else

    return Rectangle.Empty;

}


查看完整回答
反对 回复 2019-12-25
  • 3 回答
  • 0 关注
  • 467 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信