Silverlight: Centering Ellipses on a Point

Playing around with Silverlight, I decided I wanted to spike a graph that’s similar to the Blog Stats page of the site. I learned quickly that that the (x,y) coordinates for Ellipse(s) do not mean that the center of the Ellipse is at that coordinate; rather, the top-left of the Ellipse is at that coordinate. More specifically, draw a bounding rectangle as large as the ellipse, and put the top-left corner of the box at that coordinate, then center the Ellipse within the bounding box. This means that most times the Ellipse won’t even cover the coordinate!

Check out this first draft: I drew Line(s) to connect all the points, then drew Ellipse(s) with the Canvas.Left and Canvas.Top coordinates to be the same coordinates as the Line endpoints:

Silverlight Chart Draft

You’ll see they don’t correspond very well. So I needed to create an algorithm that takes in several parameters:

  1. The desired centerpoint of the Ellipse
  2. The Width and Height of the Ellipse

… and outputs the Canvas.Left and Canvas.Top of the Ellipse.

You might wonder if the StrokeThickness of the Ellipse would affect the drawing of the Ellipse. In other words, is the Stroke INSIDE OF or OUTSIDE OF the Ellipse? My tests indicate the Stroke is drawn inside the Ellipse. The following screenshot shows three circles, all with Width=Height=10. The first two have StrokeThickness=3, and the last one has StrokeThickness=5. You can see that this effectively draws a filled-in circle.

Silverlight Ellipse Stroke Thickness

The code used to get the top-left corner of the Ellipse, starting from the actual coordinate, is as follows (C#):

private double TransformX(Ellipse e, double x)
    double width = e.Width;
    double transform = width / 2.0;
    return (x - transform);

private double TransformY(Ellipse e, double y)
    double height = e.Height;
    double transform = height / 2.0;
    return (y - transform);

1 Response to “Silverlight: Centering Ellipses on a Point”

  1. 1 Maurice June 16, 2008 at 6:14 pm

    Thanks for the post! I was just poking around with this to make bubble graphs and found the placement of the ellipses a little off of what I expected. Microsoft’s documentation about the top and left of a shape as it relates to the Ellipse is spare as well. This saved me some work!

    Thanks again.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: