Home > Enterprise >  Flutter gif image to still image
Flutter gif image to still image

Time:12-07

I have a gif image to show in flutter. I want to show it's first frame as a still image. How can I achieve this thing in flutter?

I want to show it as a static image (first frame of gif image).

CodePudding user response:

You can use CustomPaint to draw the first frame of GIF and show the custom widget on the screen.

Here are the steps:

  1. Create a XFile with the GIF file:
    XFile file = XFile('xxx.gif');
    
  2. Load the XFile to ui.Image:
     Future<ui.Image> loadImage(XFile file) async {
      final data = await file.readAsBytes();
      return await decodeImageFromList(data);
    }
    
  3. Create a custom widget with CustomPaint and CustomPainter:
     Widget createCustomImage(ui.Image image) {
       return SizedBox(
         width: image.width.toDouble(),
         height: image.height.toDouble(),
         child: CustomPaint(
           painter: ImagePainter(image),
         ),
       );
     }
    
     class ImagePainter extends CustomPainter {
       ImagePainter(this. Image);
       final ui.Image image;
    
       @override
       void paint(Canvas canvas, Size size) {
         final paint = Paint()
           ..color = Colors.red
           ..strokeWidth = 5
           ..style = PaintingStyle.stroke;
    
         canvas.drawImage(image, Offset.zero, paint);
       }
    
       @override
       bool shouldRepaint(ImagePainter oldDelegate) =>
           image != oldDelegate.image;
     }
    

A little bit complicated, but it can work.

flutter gif static image

  • Related