I am trying to write a WPF application where you can draw circles on a window by double clicking it. So far I have this code:
public class ShapeAdorner : Adorner
{
private readonly Ellipse _circle;
public ShapeAdorner(UIElement adornedElement, Point circleCenter)
: base(adornedElement)
{
_circle = new Ellipse
{
Width = 10,
Height = 10,
Stroke = Brushes.Black,
StrokeThickness = 1.5
};
_circle.Margin =
new Thickness(left: circleCenter.X, top: circleCenter.Y, right: 0, bottom: 0);
base.AddVisualChild(_circle);
}
protected override Size ArrangeOverride(Size finalSize)
{
_circle.Arrange(new Rect(finalSize));
return finalSize;
}
protected override Size MeasureOverride(Size constraint)
{
_circle.Measure(constraint);
return constraint;
}
protected override Visual GetVisualChild(int index)
{
return _circle;
}
protected override int VisualChildrenCount
{
get { return 1; }
}
}
Here's the client code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(myLabel);
adornerLayer.Add(new ShapeAdorner(adornedElement: myLabel, circleCenter: e.GetPosition(myLabel)));
}
}
The circles are supposed to be centered at the point where you double click the window; however, the circles drawn by the code above are centered below and to the right of "the double click point". How can this be fixed?
EDIT: myLabel
has Height=350
and Width=525
. Let's say that I double click the point (X,Y)
; then the circle gets plotted at ((350+X)/2,(525+Y)/2)
.
EDIT 2: Just for completeness, here's the .xaml file:
<Window x:Class="Adorners.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Adorners project" Height="350" Width="525" MouseDoubleClick="Window_MouseDoubleClick">
<Grid>
<Label Name="myLabel" Content="my label" Background="Red"></Label>
</Grid>
</Window>
Where you set the margin you have to subtract the radius from the top and left properties to offset the circle.