簡體   English   中英

如何在WPF中指定畫布上橢圓形狀的位置?

[英]How to specify the position of an Ellipse shape on a canvas in WPF?

我以編程方式創建橢圓形狀但我找不到任何指定其位置的屬性。 Lines有X1,Y1,X2,Y2,但橢圓形狀上沒有中心,位置,X,Y等。 我怎樣才能做到這一點?

將形狀放在屏幕上的任意位置應該可以在Canvas面板中完成(參見@phoog的回復)。 但是,如果您將其放置在網格或其他面板中,則可以始終修改Margin屬性以將其放置在您想要的位置。

如果您想通過指定中心點而不是橢圓的左上角來執行此操作,則可以執行以下操作:

Ellipse CreateEllipse(double width, double height, double desiredCenterX, double desiredCenterY)
{
    Ellipse ellipse = new Ellipse { Width = width, Height = height };
    double left = desiredCenterX - (width / 2);
    double top  = desiredCenterY - (height/ 2);

    ellipse.Margin = new Thickness(left, top, 0, 0);
    return ellipse;
}

我沒有檢查過這在編譯器中完全符合您的要求,但希望您能得到這個想法。 同樣,使用Canvas是在非Canvas面板中使用Margin的首選方法,但計算left和top的原理仍然適用:

Canvas.SetLeft(ellipse, desiredCenterX - (width/2))
Canvas.SetTop(ellipse, desiredCenterY - (height/2))

Canvas.Left和Canvas.Top。 這些都在“如何繪制橢圓或圓形”的文檔中http://msdn.microsoft.com/en-us/library/ms751563.aspx

在C#代碼中,語法如下:

void CreateCanvasWithEllipse(double desiredLeft, double desiredTop)
{
    Canvas canvas = new Canvas();
    Ellipse ellipse = SomeEllipseConstructionMethod();
    Canvas.SetLeft(ellipse, desiredLeft);
    Canvas.SetTop(ellipse, desiredTop);
}

如果您有起點和終點以及半徑和布爾值,如果它是順時針或不是,那么使用我的函數:)

function ellipse(x1, y1, x2, y2, radius, clockwise) {
    var cBx = (x1 + x2) / 2;    //get point between xy1 and xy2
    var cBy = (y1 + y2) / 2;
    var aB = Math.atan2(y1 - y2, x1 - x2);  //get angle to bulge point in radians
    if (clockwise) { aB += (90 * (Math.PI / 180)); }
    else { aB -= (90 * (Math.PI / 180)); }
    var op_side = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) / 2;
    var adj_side = Math.sqrt(Math.pow(radius, 2) - Math.pow(op_side, 2));

    if (isNaN(adj_side)) {
        adj_side = Math.sqrt(Math.pow(op_side, 2) - Math.pow(radius, 2));
    }

    var Cx = cBx + (adj_side * Math.cos(aB));            
    var Cy = cBy + (adj_side * Math.sin(aB));
    var startA = Math.atan2(y1 - Cy, x1 - Cx);       //get start/end angles in radians
    var endA = Math.atan2(y2 - Cy, x2 - Cx);
    var mid = (startA + endA) / 2;
    var Mx = Cx + (radius * Math.cos(mid));
    var My = Cy + (radius * Math.sin(mid));
    context.arc(Cx, Cy, radius, startA, endA, clockwise);
}

暫無
暫無

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

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