flutter canvas绘制一张图片

防止类名冲突,导入dart:ui时给予别名

import 'dart:ui' as ui;
@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: CustomPaint(
        painter: ImagePaint(),
        size: Size(MediaQuery.of(context).size.width, 400),
      ),
    );
  }

ImagePaint类

class ImagePaint extends CustomPainter{
  Paint _paint;
  ui.Image _image;

  ImagePaint() { 
    _paint = Paint();
    _loadImage('assets/test.png').then((res) {
      _image = res;
    });
  }

  /// 加载图片
  Future _loadImage(String path) async {
    var data = await rootBundle.load(path);
    var codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    var info = await codec.getNextFrame();
    return info.image;
  }

  @override
  void paint(Canvas canvas, Size size) {
    if (_image != null) {
      canvas.drawImage(_image, Offset(0, 0), _paint);
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

run
flutter canvas绘制一张图片_第1张图片

你可能感兴趣的:(flutter)