Reputation: 3507
I'm trying to draw a sprite onto a CustomPaint widget. The sprite comes from an image containing multiple sprites in a grid, so I need to be able to specify the source rectangle (and preferably a destination rectangle that matches the size of the widget).
Upvotes: 5
Views: 2007
Reputation: 3507
I resolved this using canvas.drawAtlas:
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'dart:ui' as ui;
class SquarePainter extends CustomPainter {
final ui.Image theImage;
SquarePainter({this.theImage});
@override
void paint(Canvas canvas, Size size) {
canvas.drawAtlas(
theImage,
[
/* Identity transform */
RSTransform.fromComponents(
rotation: 0.0,
scale: 1.0,
anchorX: 0.0,
anchorY: 0.0,
translateX: 0.0,
translateY: 0.0)
],
[
/* A 5x5 source rectangle within the image at position (10, 10) */
Rect.fromLTWH(10.0, 10.0, 5.0, 5.0)
],
[/* No need for colors */],
BlendMode.src,
null /* No need for cullRect */,
Paint());
}
@override
bool shouldRepaint(SquarePainter oldDelegate) => false;
@override
bool shouldRebuildSemantics(SquarePainter oldDelegate) => false;
}
Upvotes: 8