Search code examples
wpfimagecanvaspixel

Canvas position to image pixel


I want to draw rectangles over an image to markup specific regions. I saw this question: Draw Rectangle over Image and it worked. I get a rectangle over the image. Now i want to get the real pixel position on the image. I know i get some data over Canvas.Left, Canvas.Top but where is the relationship between Canvas and image position?

Thanks Lyror


Solution

  • To make this work you can easily put it in a viewbox like this:

    <Viewbox> <!-- I will make this construct fit everywhere -->
        <Grid> <!-- I will be exactly the size of the image -->
    
            <Image Source="/MyImagegeWithResolutionOf1080x720p.jpg"
                Width="{Binding Source.PixelWidth, RelativeSource={RelativeSource Self}}"
                Height="{Binding Source.PixelHeight, RelativeSource={RelativeSource Self}}"
                Stretch="Fill"/>
    
            <Canvas> <!-- use me to draw your stuff -->
                <Rectangle Width="10" Height="10" Canvas.Bottom="360" Canvas.Left="540"/> <!-- I will be in the center -->
             </Canvas>
        </Grid>
    </Viewbox>