Search code examples
wpfcanvaswriteablebitmap

In WPF what is the proper method for drawing a line and PNGs on a bitmap that is attached to a canvas?


I don't do that much with WPF anymore and I always seem at a loss for the most basic things. I've tried the Googles but they're not helping.

I've got a canvas (maybe I shouldn't use a canvas?) and I want to attach an image. The only way that I could find to do this was like so:

<Canvas Grid.Column="2" HorizontalAlignment="Right" Height="822"  VerticalAlignment="Top" Width="1198" Name="MainCanvas">
    <Canvas.Background>
        <ImageBrush ImageSource="/MapDesignModule;component/MapFrame.bmp" Stretch="None" AlignmentY="Top" AlignmentX="Right"/>
    </Canvas.Background>
</Canvas>

Now, I need to draw lines on the image attached to the canvas (later I will also have to place transparent PNGs, or BMPs with white set to Alpha 0, on the image as well).

In the past I would get a writeablebitmap from the image.source but you apparently can't do that from an ImageBrush?

What is the 'proper way' to put an image on the screen and draw and blit images onto it?


Solution

  • Just put multiple Image and Line elements on top of each other in a common Panel, e.g. a Canvas:

    <Canvas>
        <Image Source="/MapDesignModule;component/MapFrame.bmp" /> 
        <Image Source="/MapDesignModule;component/Overlay.png" /> 
        <Line X1="100" Y1="100" X2="200" Y2="200" Stroke="Black" />
    </Canvas>
    

    You could also assign a name to the Canvas

    <Canvas x:Name="canvas">
    

    to access it in code behind:

    canvas.Children.Add(new Image
    {
        Source = new BitmapImage(new Uri(
            "pack://application:,,,/MapDesignModule;component/MapFrame.bmp"))
    });
    
    canvas.Children.Add(new Line
    {
        X1 = 100,
        Y1 = 100,
        X2 = 200,
        Y2 = 200
    });
    

    In case you later want to add multiple shape overlays, you may consider using an ItemsControl with an appropriate view model, e.g. as shown here: https://stackoverflow.com/a/40190793/1136211