简体   繁体   English

C#从圆边到圆边画线

[英]C# draw line from circle edge to circle edge

Let's say I have 2 points 假设我有2分

Point p1 = new Pen(100, 100);
Point p2 = new Pen(200, 150);

And I draw Ellipse for that point with given radius, that the point is in the centre of ellipse. 然后针对给定半径的那个点绘制椭圆,该点在椭圆的中心。

int radius = 5;
RectangleF rectangle = new RectangleF();
rectangle.Width = radius  * 2;
rectangle.Height = radius  * 2;
rectangle.X = Convert.ToSingle(p1.X - radius);
rectangle.Y = Convert.ToSingle(p1.Y - radius);
g.FillEllipse(brush, rectangle);
rectangle.X = Convert.ToSingle(p2.X - radius);
rectangle.Y = Convert.ToSingle(p2.Y - radius);
g.FillEllipse(brush, rectangle);

g.DrawLine(pen, p1, p2);

If I draw line between those points, I get line from one centre to other. 如果我在这些点之间画线,我将从一个中心到另一中心得到线。 At the moment I can live with that, but I would like to make, that line starts at the edge of Ellipse, so it doesn't go through it. 目前,我可以忍受这一点,但是我想做的是,那条线从Ellipse的边缘开始,所以它没有穿过它。 How could I achieve this? 我怎样才能做到这一点?

Found answer: 找到答案:

    public static PointF getPointOnCircle(PointF p1, PointF p2, Int32 radius)
    {
        PointF Pointref = PointF.Subtract(p2, new SizeF(p1));
        double degrees = Math.Atan2(Pointref.Y, Pointref.X);
        double cosx1 = Math.Cos(degrees);
        double siny1 = Math.Sin(degrees);

        double cosx2 = Math.Cos(degrees + Math.PI);
        double siny2 = Math.Sin(degrees + Math.PI);

        return new PointF((int)(cosx1 * (float)(radius) + (float)p1.X), (int)(siny1 * (float)(radius) + (float)p1.Y));
    }

You have 2 choices, 您有2个选择,

1) Draw the line first and simply overwrite it with the FillEllipse 1)先画线,然后用FillEllipse覆盖

2) Shift the start and end position of the line. 2)移动行的开始和结束位置。

to shift the line positions you'll need to: 要改变线位置,您需要:
a ) calculate the angle between the centers. a )计算中心之间的角度。
-This is Theta = tan-1(y2-y1/x2-x1) -这是Theta = tan-1(y2-y1 / x2-x1)
if using actual ellipses instead of circles: 如果使用实际的椭圆代替圆:
b ) calculate the radius of the ellipse for that angle. b )计算该角度的椭圆半径。
-This is r(Theta) = (x*y) / Sqrt(x*Cos(Theta)^2 + y*sin(Theta)^2) -这是r(Theta)=(x * y)/ Sqrt(x * Cos(Theta)^ 2 + y * sin(Theta)^ 2)
c ) calculate the offset of the line. c )计算直线的偏移量。
-This is x = rCos(Theta) and y = rSin(Theta) -这是x = rCos(Theta)和y = rSin(Theta)

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

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