Sub topic 3
Transforms, save/restore, and clipping
This chapter assumes you know Dart classes, the basics of CustomPainter, and how Paint and Path work. Each painting step below changes the canvas in some way, and save() and restore() control how far those changes reach.
Transforms and save/restore
A transform moves, rotates, or scales everything you draw after it. canvas.translate, canvas.rotate, and canvas.scale change the coordinate system. canvas.save() pushes the current state onto a stack, and canvas.restore() pops it back. Wrap each transform in a save/restore pair so it affects only the drawing you intend.
import 'package:flutter/material.dart';
class LabelPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final rect = Offset.zero & size;
final rrect = RRect.fromRectAndRadius(rect, const Radius.circular(16));
canvas.save();
canvas.clipRRect(rrect);
canvas.drawRect(
rect,
Paint()
..shader = const LinearGradient(
colors: [Colors.purple, Colors.orange],
).createShader(rect),
);
canvas.restore();
final label = TextPainter(
text: const TextSpan(
text: 'Hello',
style: TextStyle(color: Colors.white, fontSize: 24),
),
textDirection: TextDirection.ltr,
)..layout();
canvas.save();
canvas.translate(size.width / 2, size.height / 2);
canvas.rotate(-0.1);
label.paint(canvas, Offset(-label.width / 2, -label.height / 2));
canvas.restore();
}
@override
bool shouldRepaint(covariant LabelPainter oldDelegate) => false;
}Clipping
clipRRect and clipPath limit later drawing to the clip shape. The code above clips the gradient to a rounded rectangle, so the corners stay rounded.
Filling shapes with gradients
Assign a shader to Paint.shader. Call createShader(rect) on a gradient with the bounds you want it to cover. The gradient fills the shape you draw with that paint.
Drawing text with TextPainter
TextPainter lays out a TextSpan and paints it on the canvas. Call layout() before reading its width or height, then call paint() with an offset. The code above centers the label.
Blend modes and saveLayer
saveLayer creates an offscreen layer. The blend mode on its Paint applies to the whole group when restore() composites the layer.
canvas.saveLayer(rect, Paint()..blendMode = BlendMode.multiply);
canvas.drawCircle(const Offset(60, 60), 50, Paint()..color = Colors.red);
canvas.drawCircle(const Offset(100, 60), 50, Paint()..color = Colors.blue);
canvas.restore();Making painted shapes respond to touch
Override hitTest on the painter. Return true for positions inside the shape and false for the rest. The painter's rectangle is otherwise touchable.
class DotPainter extends CustomPainter {
DotPainter({required this.center, required this.radius});
final Offset center;
final double radius;
@override
void paint(Canvas canvas, Size size) {
canvas.drawCircle(center, radius, Paint()..color = Colors.red);
}
@override
bool? hitTest(Offset position) => (position - center).distance <= radius;
@override
SemanticsBuilderCallback get semanticsBuilder => (Size size) => [
CustomPainterSemantics(
rect: Rect.fromCircle(center: center, radius: radius),
properties: const SemanticsProperties(label: 'Red dot'),
),
];
@override
bool shouldRepaint(covariant DotPainter oldDelegate) =>
oldDelegate.center != center || oldDelegate.radius != radius;
}Keeping painters fast with RepaintBoundary
Keep paint() cheap and avoid creating large objects inside it. Wrap a frequently repainted CustomPaint in RepaintBoundary so its repaints do not force neighboring widgets to repaint.
Adding semantics to custom-painted widgets
CustomPaint draws pixels and exposes nothing to screen readers. Override semanticsBuilder to return a CustomPainterSemantics for each shape, with a rect and a label, as the DotPainter above does.
Exercise
Exercise
What does canvas.restore() revert?
Show answer
It pops the most recent canvas.save() and restores the transform and clip to the state they had at that save.