Sub topic 9
Transforms, save/restore, and clipping
This chapter assumes you can write a basic CustomPainter, know that paint() receives a Canvas and a Size, and can build simple shapes with Paint and Path. You should also be comfortable with Dart classes and named parameters.
By the end you will be able to move, rotate, and scale the drawing surface. You will also be able to limit drawing to a region, and use save() and restore() so these changes stay local.
The canvas has state
A Canvas is not a blank sheet that you draw on and forget. It carries state, and every later draw call uses that state. Two pieces of state matter in this chapter:
- The transform, a matrix that maps the coordinates you pass in to positions on screen.
- The clip, a region outside which nothing is drawn.
When you call canvas.translate(50, 50), you do not move any shape. You change the matrix. Every later call, such as drawCircle(Offset.zero, ...), is then interpreted relative to the new origin.
This is useful because you can describe a shape around (0, 0) and let a transform place it. A clock hand, a gear, or a spinner is easier to write this way than with trigonometry on every point.
Transform methods
Canvas offers these transform methods:
| Method | Effect |
|---|---|
| `translate(dx, dy)` | Moves the origin by `dx` and `dy` pixels. |
| `rotate(radians)` | Rotates around the current origin. Positive angles turn clockwise. |
| `scale(sx, [sy])` | Scales around the current origin. If you omit `sy`, it equals `sx`. |
| `skew(sx, sy)` | Shears the axes. |
| `transform(Float64List matrix4)` | Multiplies the current matrix by a 4x4 matrix given as 16 numbers. |
Rotation uses radians, not degrees. A full turn is 2 * math.pi. To convert, multiply degrees by math.pi / 180.
Rotation and scaling both happen around the origin of the current coordinate system, which starts at the top-left corner of the painter. To rotate a shape around its own center, move the origin to that center first. This is why the spinner from the animation chapter calls translate before rotate.
Order matters
Transforms are applied to the coordinate system one after another, and each new one works inside the result of the earlier ones. These two sequences give different pictures:
// A: move, then rotate. The rotation pivots on the moved origin.
canvas.translate(100, 100);
canvas.rotate(math.pi / 4);
// B: rotate, then move. The move now follows the rotated axes.
canvas.rotate(math.pi / 4);
canvas.translate(100, 100);In A, the origin sits at (100, 100) and the axes tilt there. In B, the axes tilt around the top-left corner first. The translate(100, 100) then slides along the tilted axes, so the origin lands at a different place.
A practical rule: to transform a shape around a pivot, use translate to the pivot, apply the rotation or scale, and draw the shape around (0, 0).
save and restore
Transforms and clips stay on the canvas until you undo them. If one part of your painter rotates the canvas, everything drawn afterward is rotated too, including later parts you did not intend to rotate.
canvas.save() pushes the current state (transform and clip) onto a stack. canvas.restore() pops the stack and returns the canvas to the saved state.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class TiltedBoxPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final fill = Paint()..color = Colors.teal;
final outline = Paint()
..color = Colors.black
..style = PaintingStyle.stroke
..strokeWidth = 2;
// Drawn first, with no transform.
canvas.drawRect(const Rect.fromLTWH(10, 10, 60, 60), outline);
canvas.save();
canvas.translate(size.width / 2, size.height / 2);
canvas.rotate(math.pi / 6);
canvas.drawRect(
Rect.fromCenter(center: Offset.zero, width: 80, height: 80),
fill,
);
canvas.restore();
// Back to the original state: this rectangle is not rotated or moved.
canvas.drawRect(
Rect.fromLTWH(size.width - 70, size.height - 70, 60, 60),
outline,
);
}
@override
bool shouldRepaint(covariant TiltedBoxPainter oldDelegate) => false;
}Use it with CustomPaint(size: const Size(200, 200), painter: TiltedBoxPainter()). The two outlined squares sit in the corners as if no transform ever happened, and only the teal square is rotated.
The stack is plain: every save() needs one matching restore(). If you call restore() more times than save(), Flutter may throw an error or log an assertion failure in debug mode. If you forget a restore(), the extra state leaks to the code after it. Flutter does clean up the canvas between frames, but inside a single paint() the leak is real.
Nested saves
You can nest save() calls. Each restore() returns to the state at the most recent unmatched save().
import 'dart:math' as math;
import 'package:flutter/material.dart';
class TickPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final center = size.center(Offset.zero);
final radius = size.shortestSide / 2 - 8;
final tick = Paint()
..color = Colors.black87
..strokeWidth = 3
..strokeCap = StrokeCap.round;
canvas.save();
canvas.translate(center.dx, center.dy);
for (var i = 0; i < 12; i++) {
canvas.save();
canvas.rotate(i * 2 * math.pi / 12);
canvas.drawLine(Offset(0, -radius), Offset(0, -radius + 12), tick);
canvas.restore();
}
canvas.restore();
}
@override
bool shouldRepaint(covariant TickPainter oldDelegate) => false;
}The outer save holds the translation to the center. The inner save holds one tick's rotation, and each restore() in the loop resets the rotation without losing the translation. You get twelve evenly spaced tick marks around a clock face.
An alternative is to rotate by a fixed step each time and never restore inside the loop. That works here because the rotations add up. It breaks as soon as each iteration needs different state, so the nested form is safer.
Check the stack with getSaveCount
canvas.getSaveCount() returns the current depth of the stack. A fresh canvas has a count of 1. It is a handy debugging tool when you suspect an unmatched save(): print it at the start and end of paint() and compare.
Clipping
A clip limits where drawing shows up. Pixels outside the clip are discarded. Three methods set the clip:
clipRect(Rect rect)for rectangles.clipRRect(RRect rrect)for rectangles with rounded corners.clipPath(Path path)for any shape you can describe with aPath.
A clip applies to every draw call after it, and it can only shrink. A second clip intersects with the first. There is no way to enlarge the region inside the same saved state, so the only way back is restore(). This is the main reason to wrap clipping in save() and restore().
import 'package:flutter/material.dart';
class ClippedStripesPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final rect = Offset.zero & size;
canvas.save();
canvas.clipRRect(RRect.fromRectAndRadius(rect, const Radius.circular(24)));
final stripe = Paint()..color = Colors.indigo;
for (var x = -size.height; x < size.width; x += 30) {
final path = Path()
..moveTo(x, size.height)
..lineTo(x + 15, size.height)
..lineTo(x + 15 + size.height, 0)
..lineTo(x + size.height, 0)
..close();
canvas.drawPath(path, stripe);
}
canvas.restore();
}
@override
bool shouldRepaint(covariant ClippedStripesPainter oldDelegate) => false;
}The diagonal stripes run past the edges of the painter, yet the result is a rounded card. The clip cuts the stripes at the rounded boundary.
Anti-aliasing and clip quality
By default, clipRect has no anti-aliasing, and clipRRect and clipPath use anti-aliased edges. Each method takes a doAntiAlias parameter. The default for clipRect and clipPath is true in current Flutter versions, but check the API docs for your version. Anti-aliased clips cost more to rasterize than hard-edged ones. For a pixel-aligned rectangle, the difference is invisible, so a plain rectangle clip is the cheapest choice.
Clipping to the painter bounds
A CustomPaint does not clip its painter by default. If you draw outside the Size, the pixels can appear over neighboring widgets. To stop this, either call canvas.clipRect(Offset.zero & size) at the start of paint() or wrap the CustomPaint in a ClipRect. The first is local to the painter. The second is declarative and keeps the painter simpler.
Reversing a clip with difference
clipPath and clipRect only keep the inside. To cut a hole, use clipRect(rect, clipOp: ClipOp.difference), which keeps everything except the rectangle. Be aware that ClipOp.difference on paths and rounded rectangles may behave differently across rendering backends and is more expensive. Test it on your target devices before you rely on it. A different way to cut holes is to build a Path with fillType = PathFillType.evenOdd, which fills the area between two nested shapes.
Common mistakes
- Forgetting
restore(). Later drawing is rotated, scaled, or clipped without warning. Pair everysave()with arestore(). - Rotating around the wrong point. If a shape swings across the screen, the origin is still at the top-left. Translate to the pivot first.
- Using degrees.
canvas.rotate(90)rotates by 90 radians. Usemath.pi / 2. - Reading transforms in the wrong order. If the result surprises you, remember each call works inside the result of the previous one.
- Expecting the clip to grow back. A clip only shrinks until you restore.
- Hit testing a transformed shape. Transforms change where pixels land, but they do not change the coordinates your
hitTestreceives. Those arrive in the painter's untransformed space, so apply the same math yourself or compare in that space.
How the pieces connect
Each save() adds a level and each restore() removes the topmost one. The states of the lower levels are untouched while you work in a higher one.
Summary
- Transforms change how coordinates map to the screen. They do not move shapes already drawn.
- Order matters. Translate to a pivot, then rotate or scale, then draw around the origin.
save()andrestore()bound the changes to transform and clip.- A clip can only shrink the drawable region, so scope it with
save()andrestore(). CustomPaintdoes not clip to its bounds on its own.
Exercise
You want to draw a small square rotated 45 degrees around its own center at (100, 100), then draw a second, unrotated circle at (40, 40) in the same paint() call. Write the sequence of canvas calls, and say why save and restore are needed.
Show answer
Call canvas.save(), canvas.translate(100, 100), canvas.rotate(math.pi / 4), then drawRect(Rect.fromCenter(center: Offset.zero, width: 40, height: 40), paint), then canvas.restore(). After that, call canvas.drawCircle(const Offset(40, 40), 10, paint). The translate moves the origin to the square's center so the rotation pivots there. Without restore, the circle would be drawn in the translated and rotated coordinate system, so it would appear at (140, 140) in the original space and be tilted. The save and restore return the canvas to its original state.
Exercise
A painter calls canvas.clipRRect(...) and then draws a rounded card. A later line in the same paint() call tries to draw a badge that sticks out past the card edge, but the badge is cut off. What is the cause, and how do you fix it?
Show answer
The clip is still active because it can only shrink the drawable region. Wrap the clipped card drawing in canvas.save() and canvas.restore(), then draw the badge after the restore so it is no longer limited by the clip.