簡體   English   中英

C#從圓邊到圓邊畫線

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

假設我有2分

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

然后針對給定半徑的那個點繪制橢圓,該點在橢圓的中心。

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);

如果我在這些點之間畫線,我將從一個中心到另一中心得到線。 目前,我可以忍受這一點,但是我想做的是,那條線從Ellipse的邊緣開始,所以它沒有穿過它。 我怎樣才能做到這一點?

找到答案:

    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));
    }

您有2個選擇,

1)先畫線,然后用FillEllipse覆蓋

2)移動行的開始和結束位置。

要改變線位置,您需要:
a )計算中心之間的角度。
-這是Theta = tan-1(y2-y1 / x2-x1)
如果使用實際的橢圓代替圓:
b )計算該角度的橢圓半徑。
-這是r(Theta)=(x * y)/ Sqrt(x * Cos(Theta)^ 2 + y * sin(Theta)^ 2)
c )計算直線的偏移量。
-這是x = rCos(Theta)和y = rSin(Theta)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM