Vaccano
Vaccano

Reputation: 82517

Center a circle in a square

Say I have the following controls (that I want to put in a Data Template):

<Rectangle Width="20" Height="20" Stroke="Black"/>
<Ellipse Width="15" Height="15" Stroke="Red" StrokeThickness="4"/>

I would like the circle to be centered exactly in the middle of the square.

Seems easy, but I am just not figuring how to do it. Everything I try is off to one side or the other by a bit.

Update:

This is my latest attempt that did not work:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="3"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="2"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="3"/>
    </Grid.RowDefinitions>
    <Rectangle Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Grid.RowSpan="3" Width="20" Height="20" Stroke="Black"/>
    <Ellipse Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="15" Height="15"  Stroke="Red" StrokeThickness="3"/>
</Grid>

It is the closest I can get.

Upvotes: 1

Views: 638

Answers (1)

McGarnagle
McGarnagle

Reputation: 102793

If you have an even-length and an odd-length shape, they can never be perfectly aligned. Like a 2-unit line and a 3-unit line, they'll always be slightly off:

---
--

So could I suggest making them both even-length, or both odd-length?

<Grid>
    <Rectangle Width="20" Height="20" Stroke="Black"/>
    <Ellipse Width="16" Height="16" Stroke="Red" StrokeThickness="4"/>
</Grid>

Upvotes: 4

Related Questions