【发布时间】:2019-08-23 03:44:44
【问题描述】:
我尝试在 Image 控件中显示加载的 gif 图像(来自文件)的单帧。我在图像控件中显示(完整)gif 图像没有问题,但我无法显示框架。出于测试目的,我总是尝试加载帧“0”(第一帧)。
XAML:
<Image>
<Image.Source>
<BitmapImage x:Name="GifFrame" AutoPlay="False" />
</Image.Source>
</Image>
我并没有在网上找到太多关于如何执行此操作的信息,但这里有一些代码片段,不幸的是,有些可能来自 WPF,我不能 100% 确定它们是否也可用于 UWP。
当打开图片时,会调用下面的“_OnImageOpened”方法(_gifStream是打开的gif图片,流还没有关闭):
private IRandomAccessStream _gifStream = null;
private async void GifImage_OnImageOpened(object sender, RoutedEventArgs e)
{
// ...
uint frameCount = 0;
if (_gifStream != null)
{
var decoder = await BitmapDecoder.CreateAsync(_gifStream);
frameCount = decoder.FrameCount;
var frame = await decoder.GetFrameAsync(0);
// Create frame image
var pixelData = await frame.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
new BitmapTransform(),
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.DoNotColorManage
).AsTask().ConfigureAwait(false);
var frameBytes = pixelData.DetachPixelData();
var memoryStream = new MemoryStream(frameBytes);
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
GifFrame.SetSource(memoryStream.AsRandomAccessStream());
});
}
}
当我设置新的源 (GifFrame.SetSource(...)) 时,窗口冻结并且没有任何反应,我必须终止该进程。在我围绕新源的设置添加 Dispatcher.RunAsync(...) 之前,我遇到了一个异常“应用程序调用了一个为不同线程编组的接口...”。
我不知道是什么原因造成的。也许我需要将字节转换为图像控件可以理解的内容,或者整个像素数据的创建是错误的?
【问题讨论】:
标签: c# uwp uwp-xaml animated-gif memorystream