Created
May 16, 2022 19:28
-
-
Save Barttje/18f5d2f277bdf5964bc540f9739c0274 to your computer and use it in GitHub Desktop.
custom painter to draw an image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter/services.dart'; | |
import 'dart:ui' as ui; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const ImageOnCanvas(), | |
); | |
} | |
} | |
class ImageOnCanvas extends StatefulWidget { | |
const ImageOnCanvas({Key? key}) : super(key: key); | |
@override | |
_ImageOnCanvasState createState() => _ImageOnCanvasState(); | |
} | |
class _ImageOnCanvasState extends State<ImageOnCanvas> { | |
@override | |
Widget build(BuildContext context) { | |
return FutureBuilder<ui.Image>( | |
future: _loadImage("assets/images/uno-reverse.png"), // a Future<String> or null | |
builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) { | |
switch (snapshot.connectionState) { | |
case ConnectionState.waiting: | |
return const Text('Image loading...'); | |
default: | |
if (snapshot.hasError) { | |
return Text('Error: ${snapshot.error}'); | |
} else { | |
return CustomPaint( | |
child: const SizedBox( | |
width: 200, | |
height: 200, | |
), | |
painter: ImagePainter(snapshot.data!)); | |
} | |
} | |
}, | |
); | |
} | |
} | |
Future<ui.Image> _loadImage(String imageAssetPath) async { | |
final ByteData data = await rootBundle.load(imageAssetPath); | |
if (data == null) { | |
throw 'Unable to read data'; | |
} | |
var codec = await ui.instantiateImageCodec(data.buffer.asUint8List()); | |
// add additional checking for number of frames etc here | |
var frame = await codec.getNextFrame(); | |
return frame.image; | |
} | |
class ImagePainter extends CustomPainter { | |
final ui.Image image; | |
ImagePainter(this.image); | |
@override | |
void paint(Canvas canvas, Size size) { | |
canvas.drawImage(image, const Offset(50, 50), Paint()); | |
} | |
@override | |
bool shouldRepaint(ImagePainter oldDelegate) { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment