美文网首页
1.15 获取两个矩形的交集

1.15 获取两个矩形的交集

作者: 陈玉涛 | 来源:发表于2019-02-20 11:38 被阅读0次
     // 判断矩形是否重叠
        private bool IsRectOverlap(Rect r1, Rect r2)
        {
            if (r1.x + r1.width > r2.x && r2.x + r2.width > r1.x
                && r1.y + r1.height > r2.y && r2.y + r2.height > r1.y)
                return true;
            else
                return false;
        }
    
        // 获取矩形的交集
        private Rect ComputeJoinRect(Rect r1, Rect r2)
        {
            if (r1.Equals(r2))
                return r1;
            if (!IsRectOverlap(r1, r2))
            {
                //Debug.Log("IsRectOverlap False." + r1.ToString() + ", " + r2.ToString());
                return r1;
            }
            Rect joinRect = new Rect();
            Vector2 p1, p2;
            // 左下角 和 右上角
            p1.x = r1.x >= r2.x ? r1.x : r2.x;
            p1.y = r1.y >= r2.y ? r1.y : r2.y;
    
            p2.x = r1.x + r1.width <= r2.x + r2.width ? r1.x + r1.width : r2.x + r2.width;
            p2.y = r1.y + r1.height <= r2.y + r2.height ? r1.y + r1.height : r2.y + r2.height;
    
            if (p2.x > p1.x && p2.y > p1.y)
            {
                joinRect = new Rect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
            }
            //Debug.Log("JoinRect: " + joinRect.ToString());
    
            return joinRect;
        }
    

    相关文章

      网友评论

          本文标题:1.15 获取两个矩形的交集

          本文链接:https://www.haomeiwen.com/subject/dimcyqtx.html