Sub topic 4
Drawing lines, rectangles, circles, and arcs
This chapter covers the four basic shapes you draw with Canvas: lines, rectangles, circles, and arcs. It assumes you know Dart classes and named parameters, can build a basic widget tree, and have seen CustomPaint, CustomPainter, and Paint in earlier chapters. You should also know that the canvas origin is the top-left corner and that Size comes from the painter's paint method.
The primitive methods at a glance
Every primitive is a method on Canvas. Each one takes geometry first and a Paint last. The Paint decides the color and whether the shape is filled or stroked. The method decides the shape.
| Method | Geometry it takes | Typical use |
|---|---|---|
| `drawLine(p1, p2, paint)` | Two `Offset` points | Axes, dividers, tick marks |
| `drawPoints(mode, points, paint)` | A list of `Offset` | Scatter plots, dotted lines |
| `drawRect(rect, paint)` | A `Rect` | Backgrounds, bars |
| `drawRRect(rrect, paint)` | An `RRect` | Rounded cards, pills |
| `drawCircle(center, radius, paint)` | An `Offset` and a `double` | Dots, avatars, knobs |
| `drawOval(rect, paint)` | A bounding `Rect` | Ellipses |
| `drawArc(rect, start, sweep, useCenter, paint)` | A bounding `Rect` and two angles | Gauges, rings, pie slices |
Geometry types you pass in
Three small value types carry the geometry.
Offset(dx, dy)is a point, or a vector from the origin.Offset.zerois the top-left corner.Size(width, height)is a width and height with no position.Rectis a position plus a size. You build one in several ways.
import 'dart:ui';
void main() {
const size = Size(200, 100);
final a = Rect.fromLTWH(10, 10, 80, 40); // left, top, width, height
final b = Rect.fromLTRB(10, 10, 90, 50); // left, top, right, bottom
final c = Rect.fromCenter(
center: const Offset(100, 50),
width: 60,
height: 20,
);
final d = Offset.zero & size; // whole canvas area
print(a == b); // true: same rectangle, two constructors
print(c.center); // Offset(100.0, 50.0)
print(d.size); // Size(200.0, 100.0)
}The & operator on an Offset and a Size is a short way to say "a rectangle starting here with this size". Offset.zero & size is the full drawing area, and you will see it in many painters.
Lines
drawLine connects two points. A line has no inside, so it is always drawn as a stroke. Whatever style the paint has, a line uses strokeWidth for its thickness. If you leave strokeWidth at its default of 0.0, Flutter draws a hairline, which is one device pixel wide.
import 'package:flutter/material.dart';
class AxesPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final axis = Paint()
..color = Colors.black87
..strokeWidth = 2
..strokeCap = StrokeCap.round;
final grid = Paint()
..color = Colors.black26
..strokeWidth = 1;
const margin = 24.0;
final origin = Offset(margin, size.height - margin);
// Light horizontal grid lines.
for (var i = 1; i <= 4; i++) {
final y = origin.dy - i * (size.height - 2 * margin) / 4;
canvas.drawLine(Offset(margin, y), Offset(size.width - margin, y), grid);
}
// Axes on top of the grid.
canvas.drawLine(origin, Offset(size.width - margin, origin.dy), axis);
canvas.drawLine(origin, Offset(margin, margin), axis);
}
@override
bool shouldRepaint(covariant AxesPainter oldDelegate) => false;
}The order of calls is the order of painting. The grid is drawn first, so the axes land on top of it. Later calls always cover earlier ones.
Many points at once
drawPoints draws a whole list in one call, which is cheaper than a loop of drawLine calls. The PointMode argument controls how the list is read.
| PointMode | Result |
|---|---|
| `points` | A dot at each point |
| `lines` | A segment for each pair: points 0-1, 2-3, and so on |
| `polygon` | One connected line through all points in order |
Dots drawn with PointMode.points are squares unless you set strokeCap = StrokeCap.round. Their size comes from strokeWidth.
Rectangles
drawRect fills a rectangle by default. Set style = PaintingStyle.stroke to draw only the outline.
drawRRect draws a rectangle with rounded corners. You build the RRect from a rectangle and a radius.
import 'package:flutter/material.dart';
class BarsPainter extends CustomPainter {
BarsPainter(this.values);
final List<double> values; // each from 0.0 to 1.0
@override
void paint(Canvas canvas, Size size) {
final slot = size.width / values.length;
final barWidth = slot * 0.6;
final fill = Paint()..color = Colors.teal;
final outline = Paint()
..color = Colors.teal.shade900
..style = PaintingStyle.stroke
..strokeWidth = 2;
for (var i = 0; i < values.length; i++) {
final height = size.height * values[i];
final rect = Rect.fromLTWH(
i * slot + (slot - barWidth) / 2,
size.height - height,
barWidth,
height,
);
final rrect = RRect.fromRectAndCorners(
rect,
topLeft: const Radius.circular(6),
topRight: const Radius.circular(6),
);
canvas.drawRRect(rrect, fill);
canvas.drawRRect(rrect, outline);
}
}
@override
bool shouldRepaint(covariant BarsPainter oldDelegate) =>
oldDelegate.values != values;
}Two details matter here. First, RRect.fromRectAndCorners lets each corner have its own radius, so the bars have round tops and square bottoms. Second, the same rrect is drawn twice with different paints, once filled and once stroked. This is the usual way to get a fill with a border.
A stroke is centered on the edge
A stroke straddles the geometry. With strokeWidth = 2, one pixel falls inside the rectangle and one falls outside. If a stroked rectangle touches the edge of the canvas, half the stroke is clipped away. Shrink the rectangle with rect.deflate(strokeWidth / 2) to keep the full stroke visible.
Circles and ovals
drawCircle takes a center and a radius. drawOval takes a bounding rectangle and fits an ellipse inside it. A circle is an oval whose bounding rectangle is a square.
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;
final colors = [Colors.red, Colors.white, Colors.red, Colors.white];
for (var i = 0; i < colors.length; i++) {
final radius = maxRadius * (colors.length - i) / colors.length;
canvas.drawCircle(center, radius, Paint()..color = colors[i]);
}
canvas.drawOval(
Rect.fromCenter(center: center, width: maxRadius, height: maxRadius / 2),
Paint()
..color = Colors.black
..style = PaintingStyle.stroke
..strokeWidth = 2,
);
}
@override
bool shouldRepaint(covariant TargetPainter oldDelegate) => false;
}The circles go from largest to smallest so each smaller one is visible on top. Using size.shortestSide keeps the target a circle when the painter's area is not square. Using size.width would let it overflow.
Arcs
An arc is a piece of an oval. drawArc takes the bounding rectangle of the full oval, a start angle, a sweep angle, a useCenter flag, and a paint.
- Angles are in radians, not degrees. A full turn is
2 * math.pi. - Angle
0points to the right, along the positive x axis (3 o'clock). - Positive angles go clockwise, because the y axis points down.
- The sweep is how far to travel from the start angle. A negative sweep goes counterclockwise.
The useCenter flag changes what is drawn.
| `useCenter` | Fill style | Stroke style |
|---|---|---|
| `false` | A segment: the arc closed by a straight chord | Only the curved edge |
| `true` | A pie slice: the arc closed through the center | The curve plus two straight radii |
To start at 12 o'clock, use a start angle of -math.pi / 2. This is how the progress ring in the spine's examples begins at the top. This painter draws a gauge with a pie slice behind a thin arc.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class GaugePainter extends CustomPainter {
GaugePainter({required this.value});
final double value; // 0.0 to 1.0
@override
void paint(Canvas canvas, Size size) {
final rect = (Offset.zero & size).deflate(10);
const start = -math.pi * 5 / 4; // lower left
const fullSweep = math.pi * 3 / 2; // 270 degrees
final track = Paint()
..color = Colors.grey.shade300
..style = PaintingStyle.stroke
..strokeWidth = 14
..strokeCap = StrokeCap.round;
final bar = Paint()
..color = Colors.deepPurple
..style = PaintingStyle.stroke
..strokeWidth = 14
..strokeCap = StrokeCap.round;
canvas.drawArc(rect, start, fullSweep, false, track);
canvas.drawArc(rect, start, fullSweep * value.clamp(0.0, 1.0), false, bar);
// A filled pie slice in the middle shows useCenter = true.
canvas.drawArc(
rect.deflate(36),
start,
fullSweep * value.clamp(0.0, 1.0),
true,
Paint()..color = Colors.deepPurple.withOpacity(0.25),
);
}
@override
bool shouldRepaint(covariant GaugePainter oldDelegate) =>
oldDelegate.value != value;
}To show it, put a CustomPaint(size: const Size(220, 220), painter: GaugePainter(value: 0.7)) in a widget tree.
Common errors
- Using degrees.
drawArcwith a sweep of90draws about 14 full turns. Convert withdegrees * math.pi / 180. - Forgetting the bounding rectangle. For
drawArcanddrawOval, the rectangle describes the whole ellipse, not just the visible part. A half circle still needs the rectangle of the full circle. - Expecting a stroke on a filled paint.
Paintdefaults toPaintingStyle.fill. AdrawLinestill works because lines ignore the fill style, butdrawRectwith a default paint gives a solid shape, not an outline. - Drawing at the wrong scale. Hard-coded numbers such as
Offset(100, 100)assume a fixed size. Derive positions fromsizeso the painter adapts to its constraints. - Allocating in
paint. Creating aPaintper bar is fine for a few shapes. For hundreds, build the paints once, outside the loop, and change onlycolorbetween draws.
Putting it together
The next painter combines all four primitives into one small speedometer face: a rounded card, tick lines around the dial, a center dot, and a needle line.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class DialPainter extends CustomPainter {
DialPainter({required this.value});
final double value; // 0.0 to 1.0
@override
void paint(Canvas canvas, Size size) {
final card = RRect.fromRectAndRadius(
Offset.zero & size,
const Radius.circular(20),
);
canvas.drawRRect(card, Paint()..color = Colors.blueGrey.shade900);
final center = size.center(Offset.zero);
final radius = size.shortestSide * 0.38;
const start = -math.pi * 5 / 4;
const sweep = math.pi * 3 / 2;
final tick = Paint()
..color = Colors.white70
..strokeWidth = 2
..strokeCap = StrokeCap.round;
for (var i = 0; i <= 10; i++) {
final angle = start + sweep * i / 10;
final dir = Offset(math.cos(angle), math.sin(angle));
canvas.drawLine(center + dir * (radius - 10), center + dir * radius, tick);
}
final needleAngle = start + sweep * value.clamp(0.0, 1.0);
canvas.drawLine(
center,
center + Offset(math.cos(needleAngle), math.sin(needleAngle)) * (radius - 14),
Paint()
..color = Colors.orangeAccent
..strokeWidth = 4
..strokeCap = StrokeCap.round,
);
canvas.drawCircle(center, 8, Paint()..color = Colors.orangeAccent);
}
@override
bool shouldRepaint(covariant DialPainter oldDelegate) =>
oldDelegate.value != value;
}Here cos and sin convert an angle to a direction. Multiplying an Offset by a double scales it, and adding two Offset values moves a point. Both operators keep the geometry short and readable.
Exercise
A painter calls canvas.drawArc(rect, 0, 90, true, paint) and shows a nearly full filled disc, not a quarter slice. What is wrong, and what is the corrected call for a quarter slice that starts at 3 o'clock and sweeps clockwise?
Show answer
The sweep is given in degrees, but drawArc expects radians, so 90 radians is about 14 turns. The correct call is canvas.drawArc(rect, 0, math.pi / 2, true, paint), with import 'dart:math' as math;. useCenter: true makes the shape a pie slice.
Exercise
You draw a stroked rectangle with strokeWidth = 8 using canvas.drawRect(Offset.zero & size, paint), and the outer edge looks thinner than the rest of the border. Why does this happen, and how do you fix it?
Show answer
A stroke is centered on the edge, so half of it (4 pixels) falls outside the canvas and is clipped. Draw (Offset.zero & size).deflate(4) instead, which moves the whole stroke inside the painter's area.
Exercise
Modify GaugePainter so the arc starts at 12 o'clock and sweeps a full circle in proportion to value. Which start angle and sweep do you use?
Show answer
Use a start angle of -math.pi / 2 and a sweep of 2 * math.pi * value. Angle 0 is 3 o'clock, so subtracting a quarter turn moves the start to the top.