我试图通过渲染画布和动画来创建一个gif。但是,gif总是空的。你必须用画布来渲染它吗?
Canvas canvas = this.MainCanvas;
int height;
int width;
if (!int.TryParse(canvas.Width.ToString(), out width))
{
throw new InvalidCastException("canvas width needs to round to an integer");
}
if (!int.TryParse(canvas.Height.ToString(), out height))
{
throw new InvalidCastException("canvas hight needs to round to an integer");
}
Storyboard sb = this.FindResource("Storyboard1") as Storyboard;
sb.Duration = new Duration(new TimeSpan(0, 0, 0, 2));
sb.Begin();
sb.Pause();
double frames = sb.Duration.TimeSpan.TotalMilliseconds / 10; // 10 frames per second
TimeSpan frameIndex = new TimeSpan(0, 0, 0, 0, 0);
BitmapEncoder encoder = new GifBitmapEncoder();
RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
for (int i = 0; i < frames; i++)
{
sb.SeekAlignedToLastTick(frameIndex);
bmp.Render(canvas);
encoder.Frames.Add(BitmapFrame.Create(bmp));
//advance frame Index
frameIndex = frameIndex.Add(new TimeSpan(0, 0, 0, 0, 10));
}
using (Stream stm = File.Create("test.gif"))
{
encoder.Save(stm);
}