Sub topic 15
Blend modes and saveLayer
This chapter assumes you can write a CustomPainter, draw shapes with Paint, and use save and restore. You will learn how a blend mode combines the pixels you draw with the pixels already on the canvas. You will also learn why many blend modes only work correctly inside saveLayer, and what that costs.
Source and destination
A blend mode is a rule for combining two colors at each pixel.
- The source is the color you are drawing now.
- The destination is the color already in the current layer at that pixel.
By default, Paint.blendMode is BlendMode.srcOver. The source is placed over the destination, and a partly transparent source lets the destination show through. Other modes use the alpha (opacity) of each side to decide which pixels survive.
You set a mode on the Paint of a single draw call:
final cutout = Paint()..blendMode = BlendMode.clear;Flutter defines about 30 modes. These are the ones you will use most often:
| Mode | Result | Typical use |
|---|---|---|
| `srcOver` | Source drawn over destination | Normal drawing (default) |
| `clear` | Pixels become fully transparent | Punching holes |
| `srcIn` | Source, kept only where the destination is opaque | Tinting an existing shape |
| `dstIn` | Destination, kept only where the source is opaque | Masks and fades |
| `dstOut` | Destination, kept only where the source is transparent | Cutting a shape out |
| `multiply` | Source and destination colors multiplied, which darkens | Shadows, tints |
| `screen` | Inverse of multiply, which lightens | Glows, highlights |
| `plus` | Color channels added together | Light effects |
Why the "current layer" matters
A blend mode sees only the pixels in the layer your painter is drawing into. That layer can already contain other content. Often it holds everything painted before your painter in the same compositing pass.
If you call drawCircle with BlendMode.clear directly, the circle clears whatever that layer contains. The result depends on what is underneath, and it can look wrong, such as a black hole instead of a see-through one. You want the blend to affect only your own drawing.
saveLayer solves this. It starts a new, empty, transparent offscreen layer. Everything you draw goes into that layer, and blend modes see only that content. When you call restore, Flutter composites the finished layer onto the canvas as one unit.
Example: a spotlight overlay
A common effect is a dark overlay with a see-through circular hole. The painter draws a translucent black rectangle, then clears a circle out of it. Both draws happen inside one layer, so the clear removes only the overlay and never the content behind it.
import 'package:flutter/material.dart';
class SpotlightPainter extends CustomPainter {
SpotlightPainter({required this.center, required this.radius});
final Offset center;
final double radius;
@override
void paint(Canvas canvas, Size size) {
final bounds = Offset.zero & size;
canvas.saveLayer(bounds, Paint());
canvas.drawRect(bounds, Paint()..color = Colors.black87);
canvas.drawCircle(center, radius, Paint()..blendMode = BlendMode.clear);
canvas.restore();
}
@override
bool shouldRepaint(covariant SpotlightPainter oldDelegate) =>
oldDelegate.center != center || oldDelegate.radius != radius;
}
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.amber, Colors.pink],
),
),
),
CustomPaint(
painter: SpotlightPainter(
center: const Offset(180, 260),
radius: 90,
),
),
],
),
),
),
);
}The CustomPaint has no child and no size, so it expands to fill the Stack. The gradient shows through the hole and is dimmed everywhere else.
What the saveLayer arguments do
The signature is saveLayer(Rect? bounds, Paint paint).
boundsis the area of the offscreen layer. Pass the smallest rectangle that contains your drawing, because the layer's memory and compositing cost grow with its area. Content drawn outside the bounds can be cropped. If you passnull, Flutter uses the whole current clip, which is the safest choice for correctness and the worst for speed.paintis applied once, when the layer is composited atrestore. Its alpha,blendMode,colorFilter, andimageFilteraffect the layer as a whole, not each draw call inside it.
The second point gives you group opacity. Suppose you draw two overlapping circles, each at 50% opacity. The overlap looks darker because both circles blend. If you want the pair to behave like one 50% shape, draw them opaque inside a layer and apply the alpha at restore:
import 'package:flutter/material.dart';
class GroupOpacityPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final bounds = Offset.zero & size;
final mid = size.center(Offset.zero);
// 0x80 is an alpha of about 50%; applied to the whole layer at restore.
canvas.saveLayer(bounds, Paint()..color = const Color(0x80000000));
canvas.drawCircle(mid.translate(-20, 0), 50, Paint()..color = Colors.red);
canvas.drawCircle(mid.translate(20, 0), 50, Paint()..color = Colors.blue);
canvas.restore();
}
@override
bool shouldRepaint(covariant GroupOpacityPainter oldDelegate) => false;
}The overlap of the two circles shows the top circle only, and the whole shape is 50% transparent. This is the same idea the Opacity widget uses for its child.
Example: masking with dstIn
Mask effects draw the content first and the mask second. With dstIn, the content (destination) is kept only where the mask (source) is opaque. This painter fades a colored rectangle to transparent on its right side:
import 'package:flutter/material.dart';
class FadeEdgePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final bounds = Offset.zero & size;
canvas.saveLayer(bounds, Paint());
canvas.drawRect(bounds, Paint()..color = Colors.teal);
final mask = Paint()
..blendMode = BlendMode.dstIn
..shader = const LinearGradient(
colors: [Colors.black, Colors.transparent],
).createShader(bounds);
canvas.drawRect(bounds, mask);
canvas.restore();
}
@override
bool shouldRepaint(covariant FadeEdgePainter oldDelegate) => false;
}The mask's own color does not appear in the output. Only its alpha matters, so black fading to transparent works as a fade-out mask.
Cost and common mistakes
saveLayer is one of the more expensive canvas operations. The GPU must render into a separate buffer, and then read it back to composite it. Use it only when you need isolation.
- Skipping saveLayer for
clear,dstIn,dstOut, orsrcIn. These modes read the destination, so they need a layer holding only your content. Without one, they act on whatever else is in the layer. - Using a layer when a clip would do. To restrict drawing to a shape,
clipPathorclipRRectis much cheaper. The difference only matters when you need partial transparency or the destination-aware blend modes. - Passing
nullor full-screen bounds for a small effect. Size the rectangle to the effect. - Calling
saveLayerrepeatedly inside loops. Each call allocates a layer. Draw many items in one layer when they share an effect. - Forgetting
restore. The layer is composited only atrestore. A missing call leaves the layer unbalanced and nothing appears as intended.
Exercise
A painter draws a full-size blue rectangle, then draws a circle with BlendMode.clear directly on the canvas, with no saveLayer. Why is this unreliable, and what is the fix?
Show answer
BlendMode.clear acts on whatever pixels are in the current layer, which may include content drawn before your painter. The result depends on that content, and the hole may not be transparent. The fix is to wrap the rectangle and the circle in canvas.saveLayer(bounds, Paint()) and canvas.restore(). The clear then affects only the isolated layer, and the finished layer composites with a true see-through hole.
Exercise
You draw two overlapping opaque circles inside saveLayer with a paint of Paint()..color = const Color(0x80000000). How does the result differ from drawing the two circles directly with 50% alpha colors?
Show answer
With the layer, the circles are drawn opaque and the 50% alpha is applied once to the combined result at restore. The overlap is not darker, because the top circle hides the one below it before the alpha is applied. With per-circle 50% alpha, the circles blend with each other, so the overlap region looks darker and mixed.