flutter - 繪制圖片

獲取圖片資源

 //方法1:獲取網絡圖片 返回ui.Image
  Future<Map<String, dynamic>> getNetImage(String url,
      {int width = 16, int height = 16}) async {
    ByteData data = await NetworkAssetBundle(Uri.parse(url)).load(url);
    // final response = await Dio().get
    //  (url, options: Options(responseType: ResponseType.bytes));
    // final data = response.data;

    print("data length is ${data.buffer.asUint8List().length}");
    ui.Codec codec = await ui.instantiateImageCodec(
      data.buffer.asUint8List(),
      targetWidth: width,
      targetHeight: height,
    );
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

//方法2.1:獲取本地圖片  返回ui.Image 需要傳入BuildContext context
  Future<ui.Image> getAssetImage2(String asset, BuildContext context,
      {width, height}) async {
    ByteData data = await DefaultAssetBundle.of(context).load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width, targetHeight: height);
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

//方法2.2:獲取本地圖片 返回ui.Image 不需要傳入BuildContext context
  Future<ui.Image> getAssetImage(String asset, {width, height}) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width, targetHeight: height);
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

繪制

_drawImage(Canvas canvas, ui.Image image) async {
    final paint = Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill
      ..strokeCap = StrokeCap.round;
    final rect = Rect.fromLTWH(0, 4, 16, 16);

    /// 繪制圓角邊框
    canvas.drawRRect(
        RRect.fromRectAndRadius(rect, Radius.circular(4.0)), paint);

    /// 繪制圓角圖片
    if (image != null) {
      canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromLTWH(1, 5, 14, 14),
            Radius.circular(4.0)),
        Paint()
          ..shader = ImageShader(
            image,
            TileMode.decal,
            TileMode.decal,
            Float64List.fromList(
                [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
          ),
      );
    } else {
      canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromLTWH(1, 5, 14, 14),
            Radius.circular(4.0)),
        Paint()..color = Colors.grey.withOpacity(0.5),
      );
    }
  }
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容