WPF - How to get canvas position on mouse click independently of the resolution and resizing

前端 未结 1 1921
终归单人心
终归单人心 2021-01-27 22:56

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 i

相关标签:
1条回答
  • 2021-01-27 23:21

    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);
    }
    
    0 讨论(0)
提交回复
热议问题