I'm trying to zoom images in UWP by using nearest neighbor scaling.
In WPF i used RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.NearestNeighbor);
. How can I get the same result but in UWP?
In WPF i used RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.NearestNeighbor);. How can I get the same result but in UWP?
In uwp, BitmapTransform
can be used for scaling images. To getting the same effects as you got by using BitmapScalingMode.NearestNeighbor
in WPF, you need to use BitmapInterpolationMode
which has NearestNeighbor
value.
Example code you can reference follows:
private async Task<IStorageFile> CreateNewImage(StorageFile sourceFile, int requestedMinSide, StorageFile resizedImageFile)
{
var imageStream = await sourceFile.OpenReadAsync();
var decoder = await BitmapDecoder.CreateAsync(imageStream);
var originalPixelWidth = decoder.PixelWidth;
var originalPixelHeight = decoder.PixelHeight;
using (imageStream)
{
using (var resizedStream = await resizedImageFile.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
double widthRatio = (double)requestedMinSide / originalPixelWidth;
double heightRatio = (double)requestedMinSide / originalPixelHeight;
uint aspectHeight = (uint)requestedMinSide;
uint aspectWidth = (uint)requestedMinSide;
uint cropX = 0, cropY = 0;
var scaledSize = (uint)requestedMinSide;
aspectHeight = (uint)(widthRatio * originalPixelHeight);
cropY = (aspectHeight - aspectWidth) / 2;
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor;
encoder.BitmapTransform.ScaledHeight = aspectHeight;
encoder.BitmapTransform.ScaledWidth = aspectWidth;
encoder.BitmapTransform.Bounds = new BitmapBounds()
{
Width = scaledSize,
Height = scaledSize,
X = cropX,
Y = cropY,
};
await encoder.FlushAsync();
}
}
return resizedImageFile;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With