GifBitmapEncoder和RenderTargetBitmap创建一个空的gif

时间:2015-03-07 19:03:01

标签: wpf rendertargetbitmap

我试图通过渲染画布和动画来创建一个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);
        }

0 个答案:

没有答案