获取图片资源
//方法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),
);
}
}