微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – Flutter – 如何使用drawImage方法在Canvas上绘制图像

我正在尝试将图像文件绘制到画布中以在Flutter中构建我的小部件.

我确实遵循了canvas documentation,但没有成功. O Image docs,thay说:

To obtain an Image object, use instantiateImageCodec.

我尝试使用instantiateImageCodec方法,但我只是得到一个Codec实例,而不是Image

如何使用canvas.drawImage获取ui.Image实例在画布上绘制的正确方法

这是我的代码一个snnipet:

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);
    });
  });
});

解决方法:

ui.Codec有一个方法getNextFrame(),它返回一个Future< FrameInfo> (你可能应该有多少帧的逻辑,但如果你知道它总是一个普通的图片,你可以跳过它.)FrameInfo一个图像属性,你需要的图像.

编辑:看看你在帖子中的代码,你不知道你在做什么.这是在CustomPainter.paint方法中定义的吗?如果是这样,你肯定会遇到问题,因为你只能在画面调用期间使用画布;你不应该在函数之外保留对它的任何引用(包括任何异步调用).

我建议使用FutureBuilder,这样只有在添加图像后才能在画布上绘图.

这看起来像这样:

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)
    }
  },
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐