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

前端 未结 1 1940
终归单人心
终归单人心 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.

    
        
            
            
        
    
    

    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)
提交回复
热议问题