Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - How to draw an Image on Canvas using DrawImage method

I'm trying to draw an image file into the canvas to compose my widget in Flutter.

I did follow canvas documentation but a did not success. O Image docs, thay say that:

To obtain an Image object, use instantiateImageCodec.

I did try use instantiateImageCodec method, but i just get a Codec instance, not a Image

How is the right way to get an instance of ui.Image to draw on canvas using canvas.drawImage

Here is a snnipet of my code:

Future<ui.Codec> _loadImage(AssetBundleImageKey key) async {
  final ByteData data = await key.bundle.load(key.name);
   if (data == null)
  throw 'Unable to read data';
   return await ui.instantiateImageCodec(data.buffer.asUint8List());
}

final Paint paint = new Paint()
  ..color = Colors.yellow
  ..strokeWidth = 2.0
  ..strokeCap = StrokeCap.butt
  ..style = PaintingStyle.stroke;

var sunImage = new ExactAssetImage("res/images/grid_icon.png");

sunImage.obtainKey(new ImageConfiguration()).then((AssetBundleImageKey key){
  _loadImage(key).then((ui.Codec codec){
    print("frameCount: ${codec.frameCount.toString()}");
    codec.getNextFrame().then((info){
      print("image: ${info.image.toString()}");
      print("duration: ${info.duration.toString()}");
      canvas.drawImage(info.image, size.center(Offset.zero), paint);
    });
  });
});
like image 836
Anderson Andrade Avatar asked Apr 11 '18 20:04

Anderson Andrade


2 Answers

This simple utility method returns a Future<UI.Image> given the image asset's path:

import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as UI;

import 'package:flutter/services.dart';

Future<UI.Image> loadUiImage(String imageAssetPath) async {
  final ByteData data = await rootBundle.load(imageAssetPath);
  final Completer<UI.Image> completer = Completer();
  UI.decodeImageFromList(Uint8List.view(data.buffer), (UI.Image img) {
    return completer.complete(img);
  });
  return completer.future;
}
like image 80
bonnyz Avatar answered Oct 24 '22 08:10

bonnyz


ui.Codec has a method getNextFrame() which returns a Future<FrameInfo> (you should probably have logic around how many frames but if you know it's always a normal picture you could skip that.) FrameInfo has an image property which is the Image you need.

EDIT: looking at the code you have in the post, it's not clear where you're doing what. Is that all defined within the CustomPainter.paint method? If so, you'd definitely have issues because you can only use the canvas for the duration of the paint call; you should not retain any references to it outside of the function (which would include any asynchronous call).

I'd recommend using a FutureBuilder so that you only draw on the canvas once you've added the image.

That would look something like this:

Future<Image> _loadImage(AssetBundleImageKey key) async {
  final ByteData data = await key.bundle.load(key.name);
  if (data == null)
    throw 'Unable to read data';
  var codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
  // add additional checking for number of frames etc here
  var frame = await codec.getNextFrame();
  return frame.image;
}

new FutureBuilder<Image>(
  future: loadImage(....), // a Future<String> or null
  builder: (BuildContext context, AsyncSnapshot<Image> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.waiting: return new Text('Image loading...');
      default:
        if (snapshot.hasError)
          return new Text('Error: ${snapshot.error}');
        else
          // ImageCanvasDrawer would be a (most likely) statless widget
          // that actually makes the CustomPaint etc
          return new ImageCanvasDrawer(image: snapshot.data)
    }
  },
)
like image 20
rmtmckenzie Avatar answered Oct 24 '22 09:10

rmtmckenzie