繁体   English   中英

如何用 C# 画一个圆并在 WindowsForm 中说明

[英]How to draw a circle with C# and to be illustrated in WindowsForm

每个人!

我在 C# 中画圆时遇到问题。 我需要在 WindowsForm 中用鼠标来说明圆,从某些点 X 和 Y 开始。这是我拥有的代码,但方法 Intersect() 不适合圆的需要,之后返回正确的插图那。

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace KursovaRabotaLibrary
{
    [Serializable]
    public class Circle : Shape
    {
        public override int Width { get; set; }
        public override int Height { get; set; }

        public override bool PointInShape(Point point)
        {
            return
                Location.X <= point.X && point.X <= Location.X + Width &&
                Location.Y <= point.Y && point.Y <= Location.Y + Height;
        }
        public override bool Intersect(Rectangle rectangle, Circle circle)
        {
            return
                Location.X < circle.Location.X + circle.Width && circle.Location.X < Location.X + Width &&
                Location.Y < circle.Location.Y + circle.Height && circle.Location.Y < Location.Y + Height;
        }
    }
}

你能帮我更好地定义方法 Intersect() 以适应圆的需要吗? 先感谢您!

您可以将此复杂测试拆分为三个简单测试的序列:

  • 如果两个对象的边界不相交,则对象也不会相交。
  • 如果圆心在矩形内(或在它的边界处),它们确实相交。
  • 如果任何矩形的角在圆内,它们确实相交。

如果圆真的是圆而不是椭圆(宽度 == 高度),并且如果 Intersect 方法应该测试矩形和圆arguments的交集(忽略它的实例变量),那么代码可能看起来像这样(未经测试):

public override bool PointInShape(Point point)
{
    var dx = point.X - Location.X;
    var dy = point.Y - Location.Y;
    // You can optimize the following
    var distance = Math.Sqrt(dx * dx + dy * dy);
    var radius = Width / 2;
    return distance < radius;
}

public override bool Intersect(Rectangle rectangle, Circle circle)
{
    var centerDistanceX = Math.Abs(circle.Location.X + circle.Width / 2 - (rectangle.Location.X + rectangle.Width / 2));
    var centerDistanceY = Math.Abs(circle.Location.Y + circle.Height / 2 - (rectangle.Location.X + rectangle.Width / 2));

    var circleRadius = circle.Width / 2;

    // Are centers too far (bounds do not intersect)?
    if (centerDistanceX > (rectangle.Width / 2 + circleRadius))
        return false;
    if (centerDistanceY > (rectangle.Height / 2 + circleRadius))
        return false;

    // Is circle center inside the rectangle?
    if (centerDistanceX <= (rectangle.Width / 2))
        return true;
    if (centerDistanceY <= (rectangle.Height / 2))
        return true;

    // Is rectangle corner inside the circle?
    var dx = centerDistanceX - rectangle.Width / 2;
    var dy = centerDistanceY - rectangle.Height / 2;
    return dx * dx + dy * dy <= circleRadius * circleRadius;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM