Area of intersection between circle and rectangle

后端 未结 7 848
陌清茗
陌清茗 2020-12-13 19:35

I\'m looking for a fast way to determine the area of intersection between a rectangle and a circle (I need to do millions of these calculations).

A specific property

7条回答
  •  孤城傲影
    2020-12-13 20:27

    Here is another solution for the problem:

    public static bool IsIntersected(PointF circle, float radius, RectangleF rectangle)
    {
    
            var rectangleCenter = new PointF((rectangle.X +  rectangle.Width / 2),
                                             (rectangle.Y + rectangle.Height / 2));
    
            var w = rectangle.Width  / 2;
            var h = rectangle.Height / 2;
    
            var dx = Math.Abs(circle.X - rectangleCenter.X);
            var dy = Math.Abs(circle.Y - rectangleCenter.Y);
    
            if (dx > (radius + w) || dy > (radius + h)) return false;
    
    
            var circleDistance = new PointF
                                     {
                                         X = Math.Abs(circle.X - rectangle.X - w),
                                         Y = Math.Abs(circle.Y - rectangle.Y - h)
                                     };
    
    
            if (circleDistance.X <= (w))
            {
                return true;
            }
    
            if (circleDistance.Y <= (h))
            {
                return true;
            }
    
            var cornerDistanceSq = Math.Pow(circleDistance.X - w, 2) + 
                        Math.Pow(circleDistance.Y - h, 2);
    
            return (cornerDistanceSq <= (Math.Pow(radius, 2)));
    }
    

提交回复
热议问题