In this example, I will share how to clip an images using png in flutter. You can certainly do it with CustomPainter. Note that there are two different classes in Flutter called Image. The normal one is a Widget; the other one (part of the ui package) is closer to a bitmap. We’ll be using the latter.
I put two images in my assets folder (cute kitten and background with transparent hole). This shows how to load the graphics from assets, convert them to bitmaps, and how to draw those to a Canvas. End result is kitten showing through hole.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | import 'dart:ui' as ui; import 'dart:typed_data'; import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show rootBundle; class ImageOverlay extends StatefulWidget { @override State createState() => new ImageOverlayState(); } class ImageOverlayState extends State<ImageOverlay> { ui.Image kitten; ui.Image hole; @override Widget build(BuildContext context) { return new SizedBox( width: 500.0, height: 500.0, child: new CustomPaint( painter: new OverlayPainter(hole, kitten), ), ); } @override void initState() { super.initState(); load('assets/hole.png').then((i) { setState(() { hole = i; }); }); load('assets/kitty.jpg').then((i) { setState(() { kitten = i; }); }); } Future<ui.Image> load(String asset) async { ByteData data = await rootBundle.load(asset); ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List()); ui.FrameInfo fi = await codec.getNextFrame(); return fi.image; } } class OverlayPainter extends CustomPainter { ui.Image hole; ui.Image kitten; OverlayPainter(this.hole, this.kitten); @override void paint(Canvas canvas, Size size) { if (kitten != null) { canvas.drawImage(kitten, Offset(0.0, 0.0), new Paint()); } if (hole != null) { canvas.drawImage(hole, Offset(0.0, 0.0), new Paint()); } } @override bool shouldRepaint(OverlayPainter oldDelegate) { return hole != oldDelegate.hole || kitten != oldDelegate.kitten; } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.