Use Ellipse with origin in the center WPF

梦想与她 提交于 2019-12-11 01:05:24

问题


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

回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/19665022/use-ellipse-with-origin-in-the-center-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!