WPF, C#: Draw a line onto existing bitmap in image control

前端 未结 2 1493
走了就别回头了
走了就别回头了 2021-01-13 00:22

I have a bitmap image in an image control

I need to draw a red line on the bitmap each time I click with the mouse on

相关标签:
2条回答
  • 2021-01-13 00:34

    When you do Graphics.FromImage, this Graphics class (and also the System.Drawing.Pen) do not belong to WPF, they are part from WinForms and they are internally using Windows' GDI+ calls to draw and cannot draw on top of WPF.

    If you didn't got an error when compiling the first line of your code, then probably your bitmapImg is a System.Drawing.Image (from WinForms) not an Image control from WPF (System.Window.Controls.Image).

    As adrianm mentioned, the easiest way will probably be to use a Grid:

    <Grid>
        <Image Source="your image" />
        <Line Name="line" Visibility="Hidden" Stroke="Red" StrokeThickness="1" />
    </Grid>
    

    Then, in your click event handler you can make the line visible and give it the coordinates you want:

    line.Visibility = Visible;
    line.X1 = mouse_x;
    line.Y1 = mouse_y;
    line.X2 = ...;
    line.Y2 = ...;
    
    0 讨论(0)
  • 2021-01-13 00:37

    You can place a canvas with the background as transparent on top of your BitmapImage and then draw the line as required. Code from xaml file:

    <Grid>
        <Image Source="C:\Users\sm143444\Desktop\download.jpg" />
        <Canvas Background="Transparent"  x:Name="draw" />
    </Grid>
    

    Code from Xaml.cs:

    public MainWindow()
        {
            InitializeComponent();
            Point startPoint = new Point(50, 50);
            Line newLine = new Line();
            newLine.Stroke = Brushes.Black;
            newLine.Fill = Brushes.Black;
            newLine.StrokeLineJoin = PenLineJoin.Bevel;
            newLine.X1 = startPoint.X;
            newLine.Y1 = startPoint.Y;
            newLine.X2 = startPoint.X + 100;
            newLine.Y2 = startPoint.Y + 100;
            newLine.StrokeThickness = 2;
            this.draw.Children.Add(newLine);
        }
    

    output

    Or you can even add a ZIndex to your image and Line so that they are laid on different layers on canvas.

    0 讨论(0)
提交回复
热议问题