Question

I have a program that I can drag, rotate and resize a System.Windows.Shapes.Ellipse in a Canvas panel.

To resize and drag the ellipse inside the canvas and always keep it center I need to correct every time its origin, because the ellipse has it origin in the top left corner.

Have a way to make the origin in the Ellipse on center by default?

Drag:

Canvas.SetTop(ellipse, newX - (ellipse.Height / 2));
Canvas.SetLeft(ellipse, newY - (ellipse.Width / 2));

Resize:

ellipse.Height = newHeight;
ellipse.Width = newWidth;

Rotate:

ellipse.RenderTransform = new RotateTransform(angle,(ellipse.Width/2),(ellipse.Height/2));
Was it helpful?

Solution

If the width and height are fixed, the simplest solution would be to set the Ellipse's RenderTransform to a TranslateTransform with X and Y set to negative offsets equal to half the ellipse's width and height, respectively:

<Ellipse Width="100" Height="100" Fill="Red">
  <Ellipse.RenderTransform>
    <TranslateTransform X="-50" Y="-50" />
  </Ellipse.RenderTransform>
</Ellipse>

Note that a caveat of using RenderTransform is that the transform is not applied to layout (and you cannot use a TranslateTransform for the LayoutTransform). That shouldn't be an issue with a Canvas because of how it handles layout, though it might be problematic with other panels.

OTHER TIPS

You can use Margin property.

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="600" Width="600">
    <Grid>
        <Canvas Width="300" Height="300">
            <Ellipse x:Name="ellipse" 
                     Canvas.Left="150" Canvas.Top="150" 
                     Width="50" Height="50" 
                     Margin="-25,-25" 
                     Stroke="Red"/>
        </Canvas>
    </Grid>
</Window>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top