How to use canvas.drawImage with a image from pubspec.yaml?

3,386 views
Skip to first unread message

Linton Achmad

unread,
May 19, 2019, 5:16:50 PM5/19/19
to Flutter Dev
Hi All,

I'm really struggling with the canvas.drawImage. How do I use use an image from my project directory that is added in pubspec.yaml?

Simon Lightfoot

unread,
May 20, 2019, 12:07:33 PM5/20/19
to Flutter Dev
You need to load the asset as bytes and decode it as a Image, you can then call canvas.drawImage to render it.

import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/painting.dart' show decodeImageFromList;

// load the image async and then draw with `canvas.drawImage(image, Offset.zero, Paint());`
Future<ui.Image> loadImageAsset(String assetName) async {
  final data = await rootBundle.load(assetName);
  return decodeImageFromList(data.buffer.asUint8List());
}


That should do it.
Simon

Linton Achmad

unread,
May 20, 2019, 4:38:25 PM5/20/19
to Flutter Dev
Simon, thanks for your help. I will give this a try and let you know how it goes.

Linton Achmad

unread,
May 20, 2019, 5:53:16 PM5/20/19
to Flutter Dev
Wow Simon! Thank you for this. It works well. I tried digging into some docs yesterday and came across image codec:


that didn't work well. Keep in touch Simon :)
Reply all
Reply to author
Forward
0 new messages