我猜当你使用 wb.Flip 时图像没有完全加载。IIRC wb.SetSource 异步运行。
WriteableBitmapEx 库中还有另一种方法,称为 FromContent。有了它,您可以从应用程序的内容中加载图像,该方法会在后台为您处理所有内容。
下面的代码片段只是加载 logo.png,翻转它并将 WriteableBitmap 分配给图像控件。
var wb = await BitmapFactory.New(1, 1).FromContent(new Uri(BaseUri, @"///assets/logo.png"));
wb = wb.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
Viewport.Source = wb;
如果您查看 WinRT 版本的 WriteableBitmapEx.FromContent 方法的源代码,您将看到流如何转换为 WriteableBitmap。使用以下代码段将任何图像格式 IRandomAccessStream 解码为 WriteableBitmap:
// Decode image format
var decoder = await BitmapDecoder.CreateAsync(fileStream);
var transform = new BitmapTransform();
var pixelData = await decoder.GetPixelDataAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);
// Swap R and B channels since it's reversed
var pixels = pixelData.DetachPixelData();
for (var i = 0; i < pixels.Length; i += 4)
{
var r = pixels[i];
var b = pixels[i + 2];
pixels[i] = b;
pixels[i + 2] = r;
}
// Copy pixels to WriteableBitmap
var wb = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
using (var bmpStream = wb.PixelBuffer.AsStream())
{
bmpStream.Seek(0, SeekOrigin.Begin);
bmpStream.Write(pixels, 0, (int)bmpStream.Length);
}
// Your original code
var newWB = wb.Flip(FlipMode.Vertical);
ImageControl.Source = newWB;
是的,这比一个代码要多得多,尤其是。如果您之前在 Silverlight 或 WPF 中这样做过。