2011-04-08 154 views

回答

18

在屏幕上任意地方把形状也许应该做所以在一个Canvas面板中(请参阅@ phoog的回复)。但是,如果您将其放置在网格或其他面板中,则始终可以修改边距属性以将其放置在您想要的位置。

如果你想通过指定的中心点,而不是椭圆的左上角这样做,你可以这样做:

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.SetLeft(ellipse, desiredCenterX - (width/2)) 
Canvas.SetTop(ellipse, desiredCenterY - (height/2)) 
+1

为什么没有Left属性? WPF是如此奇怪... – Kamil 2013-05-28 19:18:45

+1

@Kamil在这种情况下的定位是contanier的属性,而不是椭圆本身。在画布中,您可以设置Canvas.Left属性。确实很奇怪...... – heltonbiker 2013-05-29 16:18:56

+0

@heltonbiker我想这是为什么它是这样设计的,但我没有发现这个理由。 – Kamil 2013-05-31 02:04:28

13

Canvas.Left and Canvas.Top。这一切都在文档中的“如何绘制椭圆或圆” http://msdn.microsoft.com/en-us/library/ms751563.aspx

在C#代码,语法是这样的:

+0

谢谢,我试过那些代码,但不起作用。我这样做了:'ellipse.Canvas.Left',但是'Ellipse'对象没有'Canvas'属性。 – 2011-04-08 00:59:04

+1

我编辑了我的答案以显示C#语法。 Canvas.Left属性(和.Top,.Bottom,.Right)是附加属性。请参阅http://msdn.microsoft.com/en-us/library/ms749011.aspx上的概述 – phoog 2011-04-08 01:04:03

-1

如果你有起点和终点以及作为半径和布尔如果它是顺时针或不,然后使用我的功能:)

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