kyriacos_k kyriacos_k - 2 months ago 43
C# Question

DrawingVisual equivalent for UWP

I have a bitmap image of a person and I would like to draw a rectangle over the person's face. I have the coordinates of the rectangle (x, y, width, height). Like this:

enter image description here

If I were using WPF, then I could achieve this using the

DrawingVisual
and
DrawingContext
classes. Unfortunately they are not available in UWP. Are there any equivalent API's available or maybe a NuGet package to achieve the same functionality?

Answer

A solution I have come up with is encompassing the image in a Grid and placing an ItemsControl on top of it which is bound to a set of rectangles and a Canvas as a panel template:

<Grid>
    <Image Source="{Binding Image}" />
    <ItemsControl ItemsSource="{Binding Rectangles}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Helper:BindingHelper.CanvasLeftBindingPath" Value="Left" />
                <Setter Property="Helper:BindingHelper.CanvasTopBindingPath" Value="Top" />
             </Style>
        </ItemsControl.ItemContainerStyle>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Rectangle Width="{Binding Width}"
                           Height="{Binding Height}"
                           Stroke="{Binding Color}"
                           StrokeThickness="6">
                </Rectangle>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

Since Binding in a style setter is not supported in UWP I had to use a binding helper. More about that can be found here UWP Binding in Style Setter not working