Sub topic 2
The coordinate system and sizing a custom painter
This chapter assumes you know basic Dart classes, can build Flutter widget trees, and have met layout constraints and Size. You don't need animation yet.
A painter draws in numbers, and those numbers only mean something relative to a coordinate system and a size. Most "my drawing is missing" bugs come from one of two places. Either the painter was given a size of zero, or the code assumed an origin somewhere other than the top-left corner. This chapter covers both.
The coordinate system
A Canvas uses a 2D system with these rules:
- The origin
(0, 0)is the top-left corner of the painter's area. - The x axis grows to the right.
- The y axis grows downward, unlike the math convention where y grows upward.
- Units are logical pixels. Flutter scales them by the device pixel ratio, so
100is about the same physical size on different screens. - Angles are in radians and increase clockwise, because y points down.
An Offset is a point (dx, dy). A Size is a width and a height. A Rect is a rectangle with left, top, right, and bottom. The expression Offset.zero & size builds a Rect that covers the whole painter area. It is a common idiom, and the later chapters use it often.
import 'package:flutter/material.dart';
class AxesPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final bounds = Offset.zero & size;
final axis = Paint()
..color = Colors.black
..style = PaintingStyle.stroke
..strokeWidth = 2;
// Border around the whole area.
canvas.drawRect(bounds.deflate(1), axis);
// A 100x60 box whose top-left corner is at (20, 20).
canvas.drawRect(
const Rect.fromLTWH(20, 20, 100, 60),
Paint()..color = Colors.teal,
);
// A dot at the bottom-right corner, drawn with inward padding.
canvas.drawCircle(
Offset(size.width - 10, size.height - 10),
6,
Paint()..color = Colors.red,
);
}
@override
bool shouldRepaint(covariant AxesPainter oldDelegate) => false;
}
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: CustomPaint(size: const Size(240, 160), painter: AxesPainter()),
),
),
),
);
}The teal box sits near the top-left, and the red dot sits near the bottom-right. Changing 20, 20 to larger numbers moves the box right and down. If you expected "up", this is the y-down rule at work.
Where the Size comes from
paint(Canvas canvas, Size size) receives the size of the area your painter owns. That area is not your widget's full layout slot. It is the size the CustomPaint render object chose. Your painter should work from size and avoid hard-coded numbers wherever the drawing should scale.
The CustomPaint widget decides its size like this:
- With a child: the render object lays out the child and takes the child's size. The painter then draws behind or in front of the child at that size.
- Without a child: it takes the
sizeparameter and clamps it to the incoming constraints. The default isSize.zero.
import 'package:flutter/material.dart';
class BoundsPainter extends CustomPainter {
BoundsPainter(this.label, this.color);
final String label;
final Color color;
@override
void paint(Canvas canvas, Size size) {
debugPrint('$label painted at $size');
canvas.drawRect(
(Offset.zero & size).deflate(2),
Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 4,
);
}
@override
bool shouldRepaint(covariant BoundsPainter oldDelegate) =>
oldDelegate.label != label || oldDelegate.color != color;
}
class SizingDemo extends StatelessWidget {
const SizingDemo({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
// Default size is Size.zero: nothing visible.
CustomPaint(painter: BoundsPainter('zero', Colors.grey)),
const SizedBox(height: 16),
// Explicit size.
CustomPaint(
size: const Size(120, 60),
painter: BoundsPainter('fixed', Colors.blue),
),
const SizedBox(height: 16),
// Fills the leftover space because Expanded gives tight constraints.
Expanded(
child: SizedBox.expand(
child: CustomPaint(painter: BoundsPainter('expanded', Colors.green)),
),
),
],
);
}
}
void main() {
runApp(const MaterialApp(home: Scaffold(body: SizingDemo())));
}Run it and read the debug console. The first painter reports a size of zero, and the other two report real sizes. The SizedBox.expand wrapper matters because it forces tight constraints. Without it, the third painter would also be Size.zero.
Constraints win over the size parameter
The size you pass is a preference. The parent's constraints can override it:
| Situation | Resulting size |
|---|---|
| No child, no `size`, loose constraints (for example inside `Center`) | `Size.zero` |
| No child, `size: Size(200, 100)`, loose constraints | 200 × 100 |
| No child, `size: Size(200, 100)`, tight 50 × 50 constraints | 50 × 50 |
| Has a child | The child's size |
| `size: Size.infinite`, unbounded constraints (for example inside a `ListView`) | Layout error |
Sizing diagram
The diagram below shows how the render object picks the size that reaches paint().
Drawing in a size-independent way
Hard-coded coordinates break as soon as the widget is resized. Prefer one of these approaches.
Use fractions of size. Compute positions as a share of the width and height. size.center(Offset.zero) gives the middle point, and size.shortestSide gives a safe diameter for circles and squares.
import 'package:flutter/material.dart';
class TargetPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final center = size.center(Offset.zero);
final maxRadius = size.shortestSide / 2;
for (var i = 3; i >= 1; i--) {
canvas.drawCircle(
center,
maxRadius * i / 3,
Paint()..color = i.isOdd ? Colors.red : Colors.white,
);
}
}
@override
bool shouldRepaint(covariant TargetPainter oldDelegate) => false;
}Wrap this in AspectRatio(aspectRatio: 1, child: CustomPaint(painter: TargetPainter())) and it stays a centered, correctly proportioned target at any width. AspectRatio supplies tight constraints, so no size parameter is needed.
Use a design size and scale. If you have a drawing built for, say, 300 × 200, call canvas.scale(size.width / 300, size.height / 200) before drawing. Then you can keep the original numbers. The scale call is covered properly in the transforms chapter. Non-uniform scaling distorts circles and stroke widths, so keep the same ratio on both axes if you want the shapes to stay undistorted.
Edge cases
- Zero size: if
size.isEmpty, return early. Dividing bysize.widthorsize.heightwill give infinity or NaN. - Drawing outside the bounds: the canvas does not clip to your size by default. A circle larger than the area spills over neighboring widgets. Call
canvas.clipRect(Offset.zero & size)at the start ofpaint, or wrap theCustomPaintin aClipRect. - Strokes straddle their path: a stroke is centered on the edge, so a 4-pixel border drawn exactly on the edge loses half its width. That is why the examples call
deflateon the bounds. - Background and foreground:
CustomPainthas apainter(drawn behind the child) and aforegroundPainter(drawn on top). Both receive the same size. - Text and platform scale: the canvas is in logical pixels, but text may grow with the user's font scale. Size-dependent text needs care, and the text chapter returns to this.
Exercises
Exercise
A CustomPaint with painter: MyPainter() and no child is placed inside a Center. Nothing is drawn, and a debugPrint inside paint() shows "Size(0.0, 0.0)". Name two different fixes.
Show answer
Pass a size, for example CustomPaint(size: const Size(200, 200), painter: MyPainter()). Or wrap it in a widget that supplies tight constraints, such as SizedBox(width: 200, height: 200, child: CustomPaint(...)) or AspectRatio. Center gives loose constraints, and the default size is Size.zero, so the clamped result is zero.
Exercise
In paint(), you call canvas.drawCircle(const Offset(0, 0), 30, paint). Which part of the painter area do you see, and where would you move the center to put the circle in the middle?
Show answer
Only the bottom-right quarter of the circle is visible, because the origin is the top-left corner and the rest lies outside the area at negative coordinates. Use size.center(Offset.zero) as the center, which is Offset(size.width / 2, size.height / 2).
Exercise
Why does a 10-pixel-wide stroke drawn with canvas.drawRect(Offset.zero & size, paint) look thinner on the edges than expected, and what is the fix?
Show answer
A stroke is centered on the path, so half of the width (5 pixels) falls outside the painter area and is cut off by the edge of the parent's paint region or hidden. Draw the rectangle with bounds.deflate(5), which is half the stroke width.