问题
I found a lot on this subject for HTML 5 JavaScript (like so), but I have found nothing over WPF.
I have a canvas that we are creating for selecting points over a image in that canvas.
The canvas element in XAML is very simple:
<Canvas x:Name="Cnv" Grid.Column="1" Grid.Row="1" />
We are getting the coordinates from mouse click like so:
Point p = Mouse.GetPosition(Cnv);
Then, we draw something on that point:
ellipse = new Ellipse();
ellipse.Fill = Brushes.Transparent;
ellipse.Width = 20;
ellipse.Height = 20;
ellipse.Stroke = Brushes.Gray;
ellipse.StrokeThickness = 1;
Cnv.Children.Add(ellipse);
Canvas.SetLeft(ellipse, p.X-9);
Canvas.SetTop(ellipse, p.Y-5);
The problem here is, if the user resizes his screen, the canvas will also resize. And of course, the coordinates won't be right anymore.
Is there a way to draw this ellipse in a more "relative" position to the canvas? And how do I proper resize my canvas, considering these points? Is there a event handler for this?
回答1:
You may use a Viewbox and take care that the Image size is the native pixel size of its Source bitmap.
<Viewbox>
<Grid>
<Image Source="..."
Width="{Binding Source.PixelWidth, RelativeSource={RelativeSource Self}}"
Height="{Binding Source.PixelHeight, RelativeSource={RelativeSource Self}}"
MouseDown="ImageMouseDown"/>
<Canvas x:Name="canvas"/>
</Grid>
</Viewbox>
The mouse event handler places an Ellipse at the click position, regardless of the scaling, and the click position (and Ellipse size) is in bitmap pixel coordinates:
private void ImageMouseDown(object sender, MouseButtonEventArgs e)
{
var pos = e.GetPosition((IInputElement)sender);
var ellipse = new Ellipse
{
Width = 20,
Height = 20,
Fill = Brushes.Magenta
};
Canvas.SetLeft(ellipse, pos.X - 10);
Canvas.SetTop(ellipse, pos.Y - 10);
canvas.Children.Add(ellipse);
}
来源:https://stackoverflow.com/questions/63889917/wpf-how-to-get-canvas-position-on-mouse-click-independently-of-the-resolution