using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Storage;
namespace Utilities
{
public sealed class GifMaker
{
readonly List frames = new List();
private readonly uint frameWidth;
private readonly uint frameHeight;
public GifMaker(uint width, uint height)
{
frameWidth = width;
frameHeight = height;
}
public void AppendNewFrame([ReadOnlyArray]byte[] frame)
{
frames.Add(frame);
}
实现翻页式动画效果的关键是将多个单帧图片连接在一起,然后通过延时设置播放各个帧实现动画效果。
在BitmapEncoder类(MSDN)中,GoToNextFrameAsync()方法可实现在当前帧的基础上异步动态添加新的空白帧,而通过代码实现浏览各个单一图片,动态放入不同的空白帧中实现翻页动画效果。
public IAsyncInfo GenerateAsync(StorageFile file)
{
return AsyncInfo.Run(async ctx =>
{
var outStream = await file.OpenAsync(FileAccessMode.ReadWrite);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, outStream);
for (int i = 0; i < frames.Count; i++)
{
var pixels = frames;
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore,
frameWidth, frameHeight,
92.0, 92.0,
pixels);
if (i < frames.Count - 1)
await encoder.GoToNextFrameAsync();
}
await encoder.FlushAsync();
outStream.Dispose();
});
}
最后,需要设置播放帧延迟时间,以达到翻页动画效果。控制帧延迟的属性是encoder.BitmapProperties和“/grctlext/Delay”,代码如下:
public IAsyncInfo GenerateAsync(StorageFile file, int delay)
{
return AsyncInfo.Run(async ctx =>
{
var outStream = await file.OpenAsync(FileAccessMode.ReadWrite);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, outStream);
for (int i = 0; i < frames.Count; i++)
{
var pixels = frames;
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore,
frameWidth, frameHeight,
92.0, 92.0,
pixels);
if (i == 0)
{
var properties = new BitmapPropertySet
{
{
"/grctlext/Delay",
new BitmapTypedValue(delay / 10, PropertyType.UInt16)
}
};
await encoder.BitmapProperties.SetPropertiesAsync(properties);
}
if (i < frames.Count - 1)
await encoder.GoToNextFrameAsync();
}
await encoder.FlushAsync();
outStream.Dispose();
});
}
如果你是使用JavaScript作为Windows store应用开发语言,可以使用以下代码实现以上相同的效果,
var picker = new Windows.Storage.Pickers.FileSavePicker();
picker.fileTypeChoices.insert("Gif files", [".gif"]);
picker.pickSaveFileAsync().then(function(file) {
if (!file) {
return;
}
var gifMaker = new Utilities.GifMaker(800, 600);
for (var commandsIndex = 0; commandsIndex < currentFlipflop.pages.length; commandsIndex++) {
// This code is used to retrieve canvases bytes
var bytes = Flipflop.Tools.GetBytesfromFlipflop(currentFlipflop.pages[commandsIndex],
800, 600);
gifMaker.appendNewFrame(bytes);
}
gifMaker.generateAsync(file, 200).done();
});
Flipflop产生GIF动画效果演示: