我尝试使用Canvas和CustomPainter绘制图像,但是它不起作用。这是针对使用Flutter Framework的Android应用。
我只是在Windows cmd中使用命令flutter build apk
来构建应用程序。
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text('Title!')),
body: Center(
child: AspectRatio(
aspectRatio: 1.0,
child: CustomPaint(
painter: ImageEditor(),
),
),
),
);
}
}
class ImageEditor extends CustomPainter {
@override
Future paint(Canvas canvas, Size size) async {
canvas.save();
ByteData bd = await rootBundle.load("assets/sampleImagees.jpg");
final Uint8List bytes = Uint8List.view(bd.buffer);
final ui.Codec codec = await ui.instantiateImageCodec(bytes);
final ui.Image image = (await codec.getNextFrame()).image;
canvas.drawImage(image, Offset(0.0, 0.0), Paint());
canvas.save();
canvas.restore();
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
没有任何错误,但是在应用程序中什么也没有发生。这只是一个白色的屏幕。 我的代码有什么问题?
答案 0 :(得分:2)
在绘制画布之前,您的图像必须可用。通过将加载代码移到画家之外,画家现在可以按预期的方式工作:
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
ui.Image _image;
@override
void initState() {
_loadImage();
}
_loadImage() async {
ByteData bd = await rootBundle.load("assets/sampleImagees.jpg");
final Uint8List bytes = Uint8List.view(bd.buffer);
final ui.Codec codec = await ui.instantiateImageCodec(bytes);
final ui.Image image = (await codec.getNextFrame()).image;
setState(() => _image = image);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text('Title!')),
body: Center(
child: AspectRatio(
aspectRatio: 1.0,
child: CustomPaint(
painter: ImageEditor(_image),
)
),
),
);
}
}
class ImageEditor extends CustomPainter {
ui.Image image;
ImageEditor(this.image) : super();
@override
Future paint(Canvas canvas, Size size) async {
if (image != null) {
canvas.drawImage(image, Offset(0.0, 0.0), Paint());
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return image != (oldDelegate as ImageEditor).image;
}
}
请注意,您可以使用Image.asset
而非CustomPainter
轻松绘制图像:
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text('Title!')),
body: Center(
child: AspectRatio(
aspectRatio: 1.0,
child: Image.asset('assets/sampleImagees.jpg'),
),
),
);
}