FlutterFlutterFlutter

Flutter混合开发调用原生图片

2019-06-04  本文已影响19人  AJI大侠
  1. 原生实现
private void getNativeImage(String imageName , MethodChannel.Result result) {
        int drawableId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
        Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), drawableId);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        result.success(isSuccess ? baos.toByteArray() : "");
    }
  1. 观察平台通道支持数据类型,下面有一张表


    支持的数据类型
  1. Flutter实现
/// 用于读取原生资源中的图片
class NativeImageProvider extends ImageProvider<NativeImageProvider> {

  final String imageName;
  final double scale;
  final Uint8List bytes;

  const NativeImageProvider(this.imageName ,this.bytes,{this.scale: 1.0});

  @override
  ImageStreamCompleter load(key) {
    return new MultiFrameImageStreamCompleter(
        codec: _loadAsync(key),
        scale: key.scale,
        informationCollector: (StringBuffer information) {
          information.writeln('Image provider: $this');
          information.write('Image key: $key');
        });
  }

  Future<ui.Codec> _loadAsync(NativeImageProvider key) async {
    /// 读不到原生图片,开始读取images
    if (bytes == null || bytes.lengthInBytes == 0) {
      AssetBundle assetBundle = PlatformAssetBundle();
      ByteData byteData = await assetBundle.load("assets/images/$imageName.png");
      return await PaintingBinding.instance.instantiateImageCodec(byteData.buffer.asUint8List());
    } else {
      return await _loadAsyncFromFile(key, bytes);
    }
  }

  Future<ui.Codec> _loadAsyncFromFile(NativeImageProvider key, Uint8List bytes) async {
    assert(key == this);
    if (bytes.lengthInBytes == 0) {
      throw new Exception("bytes[] was empty");
    }
    return await ui.instantiateImageCodec(bytes);
  }

 @override
  Future<NativeImageProvider> obtainKey(ImageConfiguration configuration) {
    // TODO: implement obtainKey
    return SynchronousFuture<NativeImageProvider>(this);
  }
}
/// 获取原生图片
  Future getNativeImage(String imageName) async {
    Uint8List bytes =
        await channel.invokeMethod('getNativeImage', {'imageName': imageName});
    setState(() {
      imageIcon = bytes;
    });
  }
Image(image: NativeImageProvider('cc_white_return', imageIcon),),

现在我们再也不用担心图片资源浪费了happy!

上一篇 下一篇

猜你喜欢

热点阅读