几何尺寸与公差论坛

 找回密码
 注册
查看: 863|回复: 0

如何用c#编写判断一个矩形在圆内?

[复制链接]
发表于 2022-12-20 17:17:46 | 显示全部楼层 |阅读模式
Bot:还是园外

public class Rectangle
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Width { get; set; }
    public double Height { get; set; }

    public bool IsInsideCircle(double centerX, double centerY, double radius)
    {
        // 先判断四个顶点是否在圆内
        if (IsPointInsideCircle(X, Y, centerX, centerY, radius) &&
            IsPointInsideCircle(X + Width, Y, centerX, centerY, radius) &&
            IsPointInsideCircle(X + Width, Y + Height, centerX, centerY, radius) &&
            IsPointInsideCircle(X, Y + Height, centerX, centerY, radius))
        {
            // 如果四个顶点都在圆内,则矩形在圆内
            return true;
        }

        // 如果四个顶点有一个不在圆内,则判断矩形是否与圆相交
        if (IsRectangleIntersectWithCircle(X, Y, Width, Height, centerX, centerY, radius))
        {
            return true;
        }

        // 如果四个顶点都不在圆内,且矩形也没有与圆相交,则矩形在圆外
        return false;
    }

    private bool IsPointInsideCircle(double x, double y, double centerX, double centerY, double radius)
    {
        // 判断点(x, y)是否在圆(centerX, centerY, radius)内
        if ((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY) <= radius * radius)
        {
            return true;
        }
        return false;
    }

    private bool IsRectangleIntersectWithCircle(double x, double y, double width, double height, double centerX, double centerY, double radius)
    {
        // 判断矩形(x, y, width, height)是否与圆(centerX, centerY, radius)相交
        // 矩形的四条边与圆的位置关系如下:
        // 上边:有交点,全部在圆外,有部分在圆内
        // 下边:有交点,全部在圆外,有部分在圆内
        // 左边:有交点,全部在圆外,有部分在圆内
        // 右边:有交点,全部在圆外,有部分在圆内
        // 如果矩形的四条边至少有一条边有部分在圆内,则矩形与圆相交
        if (IsPointInsideCircle(x, y, centerX, centerY, radius) ||
            IsPointInsideCircle(x + width, y, centerX, centerY, radius) ||
            IsPointInsideCircle(x + width, y + height, centerX, centerY, radius) ||
            IsPointInsideCircle(x, y + height, centerX, centerY, radius))
        {
            return true;
        }
        return false;
    }
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|Archiver|小黑屋|几何尺寸与公差论坛

GMT+8, 2024-5-12 07:31 , Processed in 0.036087 second(s), 18 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表