Search code examples
c#uwpwin2d

Resizing an image using Win2D with proportional aspect ratio


I'm having an issue in my UWP Win2D app. I have an image and text being displayed in a CanvasAnimatedControl, and when I resize the window, it stretches both image and text instead of maintaining their proportions:

enter image description here

This is a portion of the code which loads and draws the image:

private void Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
{
    if (!IsLoadInProgress())
    {
        args.DrawingSession.DrawImage(_bitmap);
        DrawText(args, "...TESTING TEXT...");
    }
}

private void DrawText(CanvasAnimatedDrawEventArgs args, string text)
{
    using (var textFormat = new CanvasTextFormat()
    {
        FontSize = 96,
        FontFamily = "Segoe UI",
        FontWeight = FontWeights.Medium
    })
    {
        args.DrawingSession.DrawText(
            text,
            new Vector2(20, (float)_bitmap.Size.Height / 2),
            Colors.White,
            textFormat);
    }
}

private async Task SetImageAndSize()
{
    if (_imagePath != null)
    {
        _bitmap = await CanvasBitmap.LoadAsync(AnimatedControl, new Uri(_imagePath, UriKind.RelativeOrAbsolute));

        // Set the controls size according to image pixels to display for image
        AnimatedControl.Height = _bitmap.SizeInPixels.Height;
        AnimatedControl.Width = _bitmap.SizeInPixels.Width;
    }
}

The sample project can be downloaded here:

PROJECT LINK

What do I need to change so that the Image and Text don't stretch on resize??


Solution

  • Found my solution, I use a ViewBox:

    <Viewbox Stretch="Fill">
        <canvas:CanvasAnimatedControl x:Name="AnimatedControl" />
    </Viewbox>
    

    I had to change the Stretch on it:

    <Viewbox Stretch="UniformToFill">
        <canvas:CanvasAnimatedControl x:Name="AnimatedControl" />
    </Viewbox>