Sub topic 6
Building shapes with Path
This chapter assumes you can write a CustomPainter with paint() and shouldRepaint(), and that you know the canvas coordinate system (origin at the top left, y growing downward). You also need Paint basics: fill versus stroke style and stroke width.
canvas.drawRect and canvas.drawCircle cover simple shapes. For anything else, such as a triangle, a star, a speech bubble, a curved wave or a pie slice, you describe the outline with a Path and draw it with canvas.drawPath.
The Path model
A Path is a list of instructions that trace an outline. It has a current point, like a pen on paper. Each method either moves the pen without drawing or draws a segment from the current point.
A path is made of one or more subpaths. A subpath starts with moveTo (or with an add* method that creates its own subpath) and continues with segments until the next move. A path stores geometry only. The color, fill or stroke style, and stroke width come from the Paint you pass to drawPath. The same path can therefore be filled, stroked, used as a clip or tested for hits.
Straight segments and close
moveTo(x, y) lifts the pen and places it. lineTo(x, y) draws a straight segment. close() draws a line from the current point back to the start of the current subpath.
import 'package:flutter/material.dart';
class TrianglePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final path = Path()
..moveTo(size.width / 2, 0)
..lineTo(size.width, size.height)
..lineTo(0, size.height)
..close();
canvas.drawPath(path, Paint()..color = Colors.teal);
}
@override
bool shouldRepaint(covariant TrianglePainter oldDelegate) => false;
}close() matters mainly for strokes. A fill treats every subpath as implicitly closed, so a filled triangle looks the same with or without it. A stroked triangle without close() has a missing third side. With close(), the join style from the previous chapter also applies at the starting corner. Without it, the start and end of the line each get a cap, which leaves a visible notch.
Every segment method has a relative twin: relativeMoveTo, relativeLineTo and so on. These take offsets from the current point instead of absolute coordinates. They are convenient for shapes defined by steps, such as "go right 40, down 20".
Computing outlines in a loop
Polygons with many vertices are better generated than typed by hand. A star alternates between an outer and an inner radius around a center point.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class StarPainter extends CustomPainter {
StarPainter({this.points = 5});
final int points;
@override
void paint(Canvas canvas, Size size) {
final center = size.center(Offset.zero);
final outer = size.shortestSide / 2;
final inner = outer * 0.45;
final path = Path();
for (var i = 0; i < points * 2; i++) {
final radius = i.isEven ? outer : inner;
final angle = -math.pi / 2 + i * math.pi / points;
final p = center + Offset(math.cos(angle), math.sin(angle)) * radius;
if (i == 0) {
path.moveTo(p.dx, p.dy);
} else {
path.lineTo(p.dx, p.dy);
}
}
path.close();
canvas.drawPath(path, Paint()..color = Colors.amber);
}
@override
bool shouldRepaint(covariant StarPainter oldDelegate) =>
oldDelegate.points != points;
}Starting at -pi / 2 points the first vertex straight up, because the y axis grows downward. shouldRepaint compares points, the only input, as in the previous chapter.
Curves
Curves are defined by control points that pull the line toward them without usually touching them.
| Method | Control points | Typical use |
|---|---|---|
| `quadraticBezierTo(x1, y1, x2, y2)` | One control point, then the end point | Waves, simple bends, bubble tails |
| `cubicTo(x1, y1, x2, y2, x3, y3)` | Two control points, then the end point | Hearts, S-curves, smooth organic shapes |
| `conicTo(x1, y1, x2, y2, w)` | One control point plus a weight `w` | Exact circular and elliptical arcs |
The weight in conicTo controls how strongly the curve is pulled to the control point. A weight of 1 gives a parabola, the same as a quadratic curve. Values above 1 flatten toward the control point and values below 1 round it off.
A cubic curve is enough to draw a heart from two halves that meet at the bottom point.
import 'package:flutter/material.dart';
class HeartPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final w = size.width;
final h = size.height;
final path = Path()
..moveTo(w / 2, h * 0.9)
..cubicTo(-w * 0.2, h * 0.45, w * 0.2, -h * 0.1, w / 2, h * 0.3)
..cubicTo(w * 0.8, -h * 0.1, w * 1.2, h * 0.45, w / 2, h * 0.9)
..close();
canvas.drawPath(path, Paint()..color = Colors.redAccent);
}
@override
bool shouldRepaint(covariant HeartPainter oldDelegate) => false;
}Control points may lie outside the box. Only the curve itself needs to stay inside the painter's size to avoid being clipped.
Arcs
Arcs are the most common source of confusion, because Flutter offers several methods.
arcTo(rect, startAngle, sweepAngle, forceMoveTo)follows an ellipse inscribed inrect. Angles are in radians. Angle 0 is at the three o'clock position, and positive sweep goes clockwise on screen.arcToPoint(endPoint, radius: ..., clockwise: ..., largeArc: ...)draws an arc from the current point to a given end point. This is the form used in SVG-style path data.addArc(rect, start, sweep)adds the arc as a new subpath, so you do not need amoveTofirst.
The forceMoveTo argument of arcTo decides whether the arc starts a new subpath (true) or is connected to the current point with a straight line (false). A pie slice needs false, so the arc connects to the center point.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class PieSlicePainter extends CustomPainter {
PieSlicePainter({required this.fraction});
final double fraction; // 0.0 to 1.0
@override
void paint(Canvas canvas, Size size) {
final rect = Offset.zero & size;
final center = rect.center;
final slice = Path()
..moveTo(center.dx, center.dy)
..arcTo(rect, -math.pi / 2, 2 * math.pi * fraction, false)
..close();
canvas.drawPath(slice, Paint()..color = Colors.deepPurple);
}
@override
bool shouldRepaint(covariant PieSlicePainter oldDelegate) =>
oldDelegate.fraction != fraction;
}The path goes from the center to the arc start, along the arc, and close() returns to the center along the second straight edge.
Adding whole shapes
addRect, addOval, addRRect, addPolygon(points, close) and addPath(other, offset) each add a finished subpath without moving the pen. They are useful for composing shapes from reusable parts. addPath accepts an offset and an optional matrix, so you can build one icon-shaped path and stamp it at several positions.
You can also move or scale a finished path without rebuilding it. path.shift(offset) returns a translated copy. path.transform(matrix4Storage) takes a Float64List of 16 values from Matrix4.storage.
Fill types and holes
When a path contains overlapping or nested subpaths, Path.fillType decides which regions count as inside.
PathFillType.nonZerois the default. Winding direction matters: a nested shape drawn in the same direction as its container is filled, not cut out.PathFillType.evenOddtoggles inside and outside at each boundary crossing, so a nested shape always becomes a hole.
import 'package:flutter/material.dart';
class RingPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final rect = Offset.zero & size;
final ring = Path()
..fillType = PathFillType.evenOdd
..addOval(rect)
..addOval(rect.deflate(size.shortestSide * 0.2));
canvas.drawPath(ring, Paint()..color = Colors.blueGrey);
}
@override
bool shouldRepaint(covariant RingPainter oldDelegate) => false;
}If a hole you expected comes out filled, check the fill type first.
Combining paths
Path.combine(operation, a, b) returns a new path using PathOperation.union, intersect, difference, reverseDifference or xor. For example, Path.combine(PathOperation.difference, outer, inner) produces the same ring with real geometry rather than a fill-rule trick. Use combine when you need the result as an actual outline, for instance to clip with it or to test points against it.
Measuring and animating along a path
path.computeMetrics() returns one PathMetric per subpath. Each has a length and extractPath(start, end), which returns the part of the path between two distances. Drawing a growing prefix gives a "line drawing itself" effect.
import 'package:flutter/material.dart';
class DrawOnPainter extends CustomPainter {
DrawOnPainter({required this.progress});
final double progress; // 0.0 to 1.0
@override
void paint(Canvas canvas, Size size) {
final path = Path()
..moveTo(0, size.height / 2)
..quadraticBezierTo(size.width / 4, 0, size.width / 2, size.height / 2)
..quadraticBezierTo(
size.width * 3 / 4, size.height, size.width, size.height / 2);
final stroke = Paint()
..color = Colors.indigo
..style = PaintingStyle.stroke
..strokeWidth = 4
..strokeCap = StrokeCap.round;
for (final metric in path.computeMetrics()) {
canvas.drawPath(metric.extractPath(0, metric.length * progress), stroke);
}
}
@override
bool shouldRepaint(covariant DrawOnPainter oldDelegate) =>
oldDelegate.progress != progress;
}metric.getTangentForOffset(distance) returns a position and angle on the path, which lets you place a marker that travels along the curve.
Inspecting a path
path.getBounds()returns the tight boundingRectof the geometry. Use it to center or scale a shape you built in arbitrary units.path.contains(offset)tests a point against the filled area using the current fill type. It is the basis of hit testing for irregular shapes, covered in a later chapter.path.reset()empties a path so the object can be reused.
Common errors
- Missing
close()on a stroked shape. The final side is absent and the corner shows two caps instead of a join. - Degrees instead of radians. Arc methods take radians. Passing 90 sweeps about 14 full turns.
- Wrong
forceMoveToonarcTo. Withtrue, a pie slice loses its straight edge from the center. - Building paths in
paint()that never change. Each frame allocates and rebuilds the path. If the shape depends only onsize, that cost is small. If it involves heavy computation, such as hundreds of points, cache the path and rebuild it only whensizeor the inputs change. - Mutating a cached path inside
paint(). Appending to a storedPathon every call makes it grow without bound. Build a fresh one or callreset()first. - Expecting
containsto respect stroke width. It tests the fill region only. A thin unfilled line is never "contained".
Exercise
You build a ring from two addOval calls (outer and inner) in a Path and fill it, but the center is filled in too. Name two ways to make the center a hole.
Show answer
First, set path.fillType = PathFillType.evenOdd before drawing, so the inner oval toggles to "outside". Second, build the ring with Path.combine(PathOperation.difference, outerPath, innerPath), which produces real ring geometry that fills correctly under the default nonZero rule.
Exercise
A pie-slice painter draws only the curved edge and a floating arc, with no straight lines from the center. The code is Path()..moveTo(cx, cy)..arcTo(rect, start, sweep, true). What is wrong, and what should change?
Show answer
The last argument, forceMoveTo, is true, so the arc starts a new subpath and does not connect to the center point. Pass false so the pen draws a line from the center to the arc start. Then call close() to draw the second straight edge back to the center.