3

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));
Butzke
  • 561
  • 1
  • 14
  • 30

2 Answers2

5

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.

Mike Strobel
  • 25,075
  • 57
  • 69
  • Not worked, when I drag the ellipse its still in the top left corner the origin. – Butzke Oct 30 '13 at 10:20
  • 1
    I hadn't noticed that in your original post you are already setting the `RenderTransform` to a `RotateTransform`. Are you overwriting the `TranslateTransform`? If you want to set both, you'll need to use a `TransformGroup`. – Mike Strobel Oct 30 '13 at 10:41
  • Also, you _might_ need to set `RenderTransformOrigin="0.5,0.5"` in order to rotate around the center of the ellipse. – Mike Strobel Oct 30 '13 at 10:48
  • Isn't there a way to solve this more generally using a data binding? – Pieter Mar 06 '14 at 11:24
0

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>
Wiesław Šoltés
  • 3,114
  • 1
  • 21
  • 15