Flutter自定义CustomPainter中获取ImageShader参数ui.Image对象的方法

Posted 泸沽烟火

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter自定义CustomPainter中获取ImageShader参数ui.Image对象的方法相关的知识,希望对你有一定的参考价值。

ImageShader需要传入dart:ui包里的Image对象,ui.Image需要异步请求获取:

  Future<ui.Image> loadImage() async 
    ByteData byteData = await rootBundle.load('assets/images/target_image.jpg');
    ui.Codec codec =
        await ui.instantiateImageCodec(byteData.buffer.asUint8List());
    ui.FrameInfo frameInfo = await codec.getNextFrame();
    return frameInfo.image;
  

建议在State初始化的时候获取异步资源,再传入到自定义的CustomPainter中,否则会报错:

class MyHomePage extends StatefulWidget 
  @override
  _MyHomePageState createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
  ui.Image _image;

  @override
  void initState() 
    super.initState();
    loadImage().then((value) 
      setState(() 
        _image = value;
      );
    );
  

  Future<ui.Image> loadImage() async 
    ByteData byteData = await rootBundle.load('assets/images/target_image.jpg');
    ui.Codec codec =
        await ui.instantiateImageCodec(byteData.buffer.asUint8List());
    ui.FrameInfo frameInfo = await codec.getNextFrame();
    return frameInfo.image;
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: _image == null
            ? Center(
                child: Text("loading..."),
              )
            : CustomPaint(
                painter: PaperPainter(_image),
              ),
      ),
    );
  


class PaperPainter extends CustomPainter 
  ui.Image _image;
  Paint _paint = Paint();

  PaperPainter(this._image);

  @override
  void paint(Canvas canvas, Size size) async 
    print("image: $_image");

    _paint.shader = ImageShader(_image, TileMode.repeated, TileMode.repeated,
        Float64List.fromList([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]));

    canvas.drawCircle(Offset(100, 100), 50, _paint);
  

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) 
    return true;
  

网上另一种获取ui.Image对象的方法:

  Future<ui.Image> loadImage() 
    ImageProvider provider = AssetImage('assets/images/target_image.jpg');
    Completer<ui.Image> completer = Completer<ui.Image>();
    ImageStreamListener listener;
    ImageStream stream = provider.resolve(ImageConfiguration());
    listener = ImageStreamListener((info, syno) 
      final ui.Image image = info.image;
      completer.complete(image);
      stream.removeListener(listener);
    );
    stream.addListener(listener);
    return completer.future;
  

 

以上是关于Flutter自定义CustomPainter中获取ImageShader参数ui.Image对象的方法的主要内容,如果未能解决你的问题,请参考以下文章

Flutter自定义CustomPainter中获取ImageShader参数ui.Image对象的方法

Flutter自定义绘制组件

Flutter CustomPaint 使用介绍

Flutter:如何将 Canvas/CustomPainter 保存到图像文件中?

Flutter 如何将裁剪器添加到 fl_chart (CustomPainter)

说说Flutter中的RepaintBoundary