使用 Bitmaptransform 缩放图像会在 win2d 中产生模糊图像

Scaling image using Bitmaptransform gives blured images in win2d

这是我试过的:

var decoder = await BitmapDecoder.CreateAsync(fileStream);
BitmapTransform bitmapTransform = new BitmapTransform();
bitmapTransform.ScaledHeight = 300;
bitmapTransform.ScaledWidth = 800;

var pixelProvider = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    bitmapTransform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage);

byte[] by = pixelProvider.DetachPixelData();
CanvasBitmap cb = CanvasBitmap.CreateFromBytes(sender,by,800,300,Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8X8UIntNormalized);

我在CanvasControl的Draw事件中做了什么:

private  void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
args.DrawingSession.DrawImage(cb);
}

由于缩放,图像变得模糊。我该如何解决这个问题?我需要在 运行 时间动态更改图像的宽度和高度,我该怎么做? 我的原始图像:

绘制后(模糊图像):

出现这种情况,说明你的图片分辨率超过了你给的控件尺寸。并且像素走样是由插值算法造成的。

默认情况下,图片缩放时使用的插值算法是Linear,如果想在较小的控件上渲染更大分辨率的图片,可以使用Fant算法。

bitmapTransform.ScaledHeight = 300;
bitmapTransform.ScaledWidth = 800;
bitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;

如果打算动态改变图片的宽高,建议使用ViewBox作为CanvasControl容器

<Viewbox Stretch="Uniform" StretchDirection="Both" x:Name="MyViewbox">
    <xaml:CanvasControl />
</Viewbox>

然后您可以在运行时更改 Viewbox 的大小。

MyViewbox.Width = 400;
MyViewbox.Height = 150;

谢谢。

您可以使用 Win2d 特效快速完成工作。

 var ScaledImage = new Microsoft.Graphics.Canvas.Effects.ScaleEffect(
Source = source, new Vector2(2f, 2f);)

上面的函数产生了一个 ScaleEffect,它实现了 ICanvasBitmap 所以你可以直接用 DrawingSession.DrawImage

渲染它