Flutter-如何使用DrawImage方法在画布上绘制图像 [英] Flutter - How to draw an Image on Canvas using DrawImage method

查看:437
本文介绍了Flutter-如何使用DrawImage方法在画布上绘制图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我确实遵循了画布文档,但是没有成功.O 图像文档,说:

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

要获取Image对象,请使用InstantiateImageCodec.

To obtain an Image object, use instantiateImageCodec.

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

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

如何使用 canvas.drawImage

这是我的代码的摘要:

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

推荐答案

此简单的实用程序方法在给定图像资源的路径的情况下返回 Future< UI.Image> .

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

这篇关于Flutter-如何使用DrawImage方法在画布上绘制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆