How to render 'dart:ui' Image into Flutter?
I have some images loaded into memory that are of type Image from 'dart:ui'. But I need to render these images in my Flutter app. How do I do this?
You can convert ui.Image to Image widget
final pngBytes = await uiimage.toByteData(format: ImageByteFormat.png);
return Image.memory(
Uint8List.view(pngBytes!.buffer)
);
I ended up creating a custom widget to solve this problem. Here is the full code:
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
class UIImage extends StatelessWidget {
final ui.Image image;
const UIImage({
Key key,
@required this.image,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return CustomPaint(painter: _UIImagePainter(image));
}
}
class _UIImagePainter extends CustomPainter {
final ui.Image image;
_UIImagePainter(this.image);
@override
void paint(Canvas canvas, Size size) {
canvas.drawImageRect(
image,
Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
Rect.fromLTWH(0, 0, size.width, size.height),
Paint(),
);
}
@override
bool shouldRepaint(_UIImagePainter oldDelegate) {
return image != oldDelegate.image;
}
}