使用具有比例宽高比的Win2D调整图像大小

时间:2018-04-20 16:03:24

标签: c# uwp win2d

我的UWP Win2D应用中存在问题。我有一个图像和文本显示在CanvasAnimatedControl中,当我调整窗口大小时,它会拉伸图像和文本而不是保持它们的比例:

enter image description here

这是加载和绘制图像的代码的一部分:

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;
    }
}

示例项目可以在这里下载:

PROJECT LINK

我需要更改什么,以便在调整大小时图像和文字不会延伸?

1 个答案:

答案 0 :(得分:0)

找到我的解决方案,我使用ViewBox:

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

我不得不更改Stretch:

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