在 Flutter 中 drawImage 或 paintImage 都不能正常工作 [英] Either drawImage or paintImage doesn't work properly in Flutter
问题描述
我基本上想在画布上显示我在资产文件夹中的图像.
I basically want to show an image that I have in the assets folder onto the canvas.
import 'package:flutter/material.dart' as ui;
...
ui.Image img = ui.Image.asset("images/some_image.png");
ui.paintImage(canvas: canvas, image: img);
当我尝试将 img 分配给 paintImage 的图像时收到以下错误消息.
And have got the following error message when I tried to assign img to paintImage's image.
参数类型'Image (C:ABCflutterpackagesflutterlibsrcwidgetsimage.dart)'不能分配给参数类型'Image (C:ABCflutterincachepkgsky_enginelibuipainting.dart)'.
The argument type 'Image (C:ABCflutterpackagesflutterlibsrcwidgetsimage.dart)' can't be assigned to the parameter type 'Image (C:ABCflutterincachepkgsky_enginelibuipainting.dart)'.
我真的不知道会出什么问题,我见过其他代码与 ui.Image 有类似的方法.
I don't really know what could go wrong, I have seen other codes that had a similar approach with ui.Image.
请指教.
推荐答案
flutter中有两个叫Image
的类,在不同的包中.
There are two classes called Image
in flutter, in different packages.
有 Widget,其行为类似于小部件,可以通过其命名构造函数从资产、内存或网络中实例化.
There's the Widget, which behaves like a widget and can be instantiated from an asset, from memory or from the network through its named constructors.
还有 ui 包 Image在较低级别进行绘制,例如在 CustomPainter
中.由于此版本位于 ui
包中,因此通常使用 ui
前缀导入,如下所示:
There's also the ui package Image which is used when painting at a lower level, for example in a CustomPainter
. Since this version is in the ui
package it's normally imported with the ui
prefix like this:
import 'dart:ui' as ui;
不要将 material
导入为 ui
!这会导致很多混乱.
Don't import material
as ui
! That will lead to a lot of confusion.
要制作小部件,请使用 Image.asset
构造函数,并传递资产名称.
To make a widget, use the Image.asset
constructor, passing the asset name.
要从资产中创建 ui.Image
,请使用以下代码段:
To make a ui.Image
from an asset use this snippet:
Future<ui.Image> load(String asset) async {
ByteData data = await rootBundle.load(asset);
ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
ui.FrameInfo fi = await codec.getNextFrame();
return fi.image;
}
这篇关于在 Flutter 中 drawImage 或 paintImage 都不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!