Joan Venge
Joan Venge

Reputation: 331480

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

I am programmatically creating an Ellipse shape but I can't find any property that specifies its position. Lines have X1, Y1, X2, Y2, but there is no Center, Position, X, Y, etc on an Ellipse shape. How can I do this?

Upvotes: 19

Views: 62308

Answers (2)

phoog
phoog

Reputation: 43066

Canvas.Left and Canvas.Top. It's all in the documentation on "How to Draw an Ellipse or a Circle" http://msdn.microsoft.com/en-us/library/ms751563.aspx

In C# code, the syntax would be this:

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

Upvotes: 15

viggity
viggity

Reputation: 15237

Putting shapes in arbitrary places on the screen should probably be done so in a Canvas Panel (see @phoog's response). But if you're placing this in a Grid or some other panel instead, you could always modify the Margin property to place it where you want it.

If you wanted to do so by specifying the center point instead of the top left corner of the ellipse, you could do this:

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

I haven't checked that this does exactly what you want in the compiler, but hopefully you get the idea. Again, using Canvas would be the prefered method over using Margin inside of a non-Canvas panel, but the same principle of calculating left and top would still apply:

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

Upvotes: 25

Related Questions