0

I am attempting to create a gif by rendering a canvas and animation. However, the gif is always empty. Is there something special that you must do with the canvas to render it?

        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);
        }
Roger
  • 2,063
  • 4
  • 32
  • 65
  • A few questions: is the gif empty as in 0x0 or is it blank? Is the canvas forest rendered to the display? What is the ActualWidth and ActualHeight of the Canvas? Does this work for a non-gif encoder? – NextInLine Mar 08 '15 at 04:46
  • I am testing with a small size: 96x96. In photoshop, it is a clear 96x96 gif. I also switched to using ActualWidth/ActualHeight. I switched to PngBitmapEncoder and got the exact same result: a transparent 96x96 image. – Roger Mar 08 '15 at 14:30
  • My guess is either (1) the controls on the canvas aren't being measured and arranged before encoding, or (2) you aren't explicitly sizing the controls and so they aren't actually sizing since Canvas just asks controls what size they need rather than telling them what space they have. – NextInLine Mar 08 '15 at 14:48

0 Answers0