Sub topic 5
Fill, stroke, caps, and joins
This chapter covers how Paint decides whether a shape is filled or outlined, and how stroked lines look at their ends and corners. It assumes you can write a CustomPainter subclass, know that paint() receives a Canvas and a Size, and have drawn basic primitives such as lines, rectangles, and circles. The earlier chapters covered those.
Paint is a bundle of style settings
A Canvas method such as drawCircle or drawPath describes geometry only. The Paint object you pass in controls how that geometry becomes pixels. Color, fill or stroke, line width, end shape, corner shape, and anti-aliasing all live on Paint.
Two properties decide the basic look of a shape:
styleis aPaintingStyle, eitherPaintingStyle.fillorPaintingStyle.stroke.strokeWidthis the line thickness in logical pixels. It only matters when the style isstroke.
The default style is PaintingStyle.fill. If you set strokeWidth but forget to set style, nothing visibly changes, and this is the most common mistake in this area.
import 'package:flutter/material.dart';
class FillVsStrokePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final fill = Paint()
..color = Colors.teal
..style = PaintingStyle.fill;
final stroke = Paint()
..color = Colors.teal
..style = PaintingStyle.stroke
..strokeWidth = 6;
final left = Rect.fromLTWH(0, 0, size.width / 2 - 8, size.height);
final right = Rect.fromLTWH(size.width / 2 + 8, 0, size.width / 2 - 8, size.height);
canvas.drawRect(left, fill);
canvas.drawRect(right.deflate(3), stroke);
}
@override
bool shouldRepaint(covariant FillVsStrokePainter oldDelegate) => false;
}
// Usage:
// CustomPaint(size: const Size(240, 100), painter: FillVsStrokePainter())The right rectangle is deflated by half the stroke width (3 pixels). The reason is explained in the next section.
Where a stroke sits relative to the geometry
A stroke is centered on the geometry's edge. Half the line width lies inside the shape and half lies outside. A strokeWidth of 6 on a rectangle that exactly fills the canvas puts 3 pixels outside the canvas, and those 3 pixels are clipped by the CustomPaint bounds if nothing else extends them.
This matters in practice whenever a shape touches the edge of the painter's area. The fix is to inset the geometry by half the stroke width, using Rect.deflate, or by computing a smaller radius.
import 'package:flutter/material.dart';
class InsetStrokePainter extends CustomPainter {
static const double strokeWidth = 10;
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.deepPurple
..style = PaintingStyle.stroke
..strokeWidth = strokeWidth;
final safeRect = (Offset.zero & size).deflate(strokeWidth / 2);
canvas.drawRRect(
RRect.fromRectAndRadius(safeRect, const Radius.circular(20)),
paint,
);
}
@override
bool shouldRepaint(covariant InsetStrokePainter oldDelegate) => false;
}The progress ring from the animation material uses the same idea: it calls rect.deflate(6) for a stroke width of 12.
Hairlines
A strokeWidth of 0.0 is the default and draws a "hairline", a line that is always one device pixel wide whatever the scale. Hairlines are useful for grids, but they do not grow when you apply canvas.scale. Any positive width scales with transforms.
Stroke caps
A cap is the shape at the open ends of a stroked line or path. It is set with strokeCap, a StrokeCap value.
| Value | Appearance | Extends past the end point? |
|---|---|---|
| `StrokeCap.butt` | Flat edge exactly at the end point. This is the default. | No |
| `StrokeCap.round` | Semicircle centered on the end point. | Yes, by half the stroke width |
| `StrokeCap.square` | Flat edge pushed out past the end point. | Yes, by half the stroke width |
Caps only apply to open ends. A closed path, such as a circle or a rectangle, has no ends, so strokeCap has no effect on it. Caps do apply to each dash or each separate sub-path of a path with several moveTo calls.
A zero-length line is a useful edge case. With StrokeCap.butt it draws nothing. With round it draws a dot, and with square it draws a square. This is a cheap way to draw a dot of an exact width.
import 'package:flutter/material.dart';
class CapsPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
const caps = [StrokeCap.butt, StrokeCap.round, StrokeCap.square];
final rowHeight = size.height / caps.length;
for (var i = 0; i < caps.length; i++) {
final y = rowHeight * i + rowHeight / 2;
final paint = Paint()
..color = Colors.indigo
..style = PaintingStyle.stroke
..strokeWidth = 16
..strokeCap = caps[i];
canvas.drawLine(Offset(30, y), Offset(size.width - 30, y), paint);
// Thin guide marks show where the geometry really ends.
final guide = Paint()
..color = Colors.red
..strokeWidth = 1;
canvas.drawLine(Offset(30, y - 14), Offset(30, y + 14), guide);
canvas.drawLine(Offset(size.width - 30, y - 14), Offset(size.width - 30, y + 14), guide);
}
}
@override
bool shouldRepaint(covariant CapsPainter oldDelegate) => false;
}The red guides show that the round and square lines poke past the geometry's end points, while the butt line stops exactly at them. If you are drawing a progress arc that must end at a precise angle, remember this overshoot. A round cap makes the arc look slightly longer than its sweep angle.
Stroke joins
A join is the shape where two segments of a path meet at a corner. It is set with strokeJoin, a StrokeJoin value.
| Value | Appearance |
|---|---|
| `StrokeJoin.miter` | Sharp pointed corner. This is the default. |
| `StrokeJoin.round` | Rounded corner. |
| `StrokeJoin.bevel` | Corner cut flat. |
Joins only matter where a path changes direction with a corner. A straight line, a smooth curve, and a circle have no corners, so strokeJoin does nothing for them.
Miter limit
A miter join extends to a point. The sharper the angle, the longer that point becomes. To stop very sharp angles from producing long spikes, Flutter uses strokeMiterLimit, which defaults to 4.0. When the ratio of the miter length to the stroke width exceeds the limit, the join falls back to a bevel. Raise the limit to keep pointed corners on narrow angles, or switch to round if you want predictable corners.
import 'package:flutter/material.dart';
class JoinsPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
const joins = [StrokeJoin.miter, StrokeJoin.round, StrokeJoin.bevel];
final cellWidth = size.width / joins.length;
for (var i = 0; i < joins.length; i++) {
final left = cellWidth * i + 16;
final path = Path()
..moveTo(left, size.height - 20)
..lineTo(left + (cellWidth - 32) / 2, 20)
..lineTo(left + cellWidth - 32, size.height - 20);
final paint = Paint()
..color = Colors.orange.shade800
..style = PaintingStyle.stroke
..strokeWidth = 18
..strokeJoin = joins[i]
..strokeCap = StrokeCap.butt;
canvas.drawPath(path, paint);
}
}
@override
bool shouldRepaint(covariant JoinsPainter oldDelegate) => false;
}Each peak is drawn as an open path, so the caps stay butt and only the join at the top differs between the three shapes.
Combining fill and stroke
A single Paint is either fill or stroke, never both. To draw a filled shape with an outline, draw it twice with two Paint objects. Draw the fill first and the stroke second, so the outline sits on top.
import 'package:flutter/material.dart';
class OutlinedBadgePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final path = Path()
..moveTo(size.width / 2, 8)
..lineTo(size.width - 8, size.height / 2)
..lineTo(size.width / 2, size.height - 8)
..lineTo(8, size.height / 2)
..close();
final fill = Paint()
..color = Colors.amber
..style = PaintingStyle.fill;
final outline = Paint()
..color = Colors.brown
..style = PaintingStyle.stroke
..strokeWidth = 6
..strokeJoin = StrokeJoin.round;
canvas.drawPath(path, fill);
canvas.drawPath(path, outline);
}
@override
bool shouldRepaint(covariant OutlinedBadgePainter oldDelegate) => false;
}Calling close() joins the last point back to the first with a real corner, so strokeJoin applies there too. Without close(), the start point would get two caps instead of a join.
Reusing Paint objects
paint() can run many times per second during an animation. Allocating a new Paint on each call is cheap but not free. If the style never changes, you can create the Paint as a final field of the painter and reuse it. If a value such as color depends on the painter's constructor arguments, set it in the field initializer or mutate it at the start of paint().
import 'package:flutter/material.dart';
class ReusePaintPainter extends CustomPainter {
ReusePaintPainter({required this.color});
final Color color;
final Paint _line = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 4
..strokeCap = StrokeCap.round;
@override
void paint(Canvas canvas, Size size) {
_line.color = color;
canvas.drawLine(Offset(10, size.height / 2), Offset(size.width - 10, size.height / 2), _line);
}
@override
bool shouldRepaint(covariant ReusePaintPainter oldDelegate) =>
oldDelegate.color != color;
}Keep reuse simple. Mutating a shared Paint between draw calls is safe, because Canvas reads the values when each draw call is made, but it is easy to forget which properties you changed earlier.
Anti-aliasing
Paint.isAntiAlias is true by default and smooths the edges of shapes. Turning it off gives hard, pixelated edges, which is only useful for deliberate pixel-art effects or for axis-aligned rectangles that you have already snapped to whole pixels. Leave it on otherwise.
Common errors
- Setting
strokeWidthwithoutstyle. The paint stays a fill and the width is ignored. - Clipped outlines at the edge. Half the stroke falls outside the canvas. Deflate the geometry by
strokeWidth / 2. - Expecting caps on closed shapes. A circle or a closed path has no ends, so caps do nothing.
- Expecting joins on curves. Joins affect corners only.
- Spikes on sharp angles. A miter join beyond the miter limit is cut to a bevel. Use
StrokeJoin.roundor raisestrokeMiterLimit. - Arc looks too long. Round and square caps extend past the end angle by half the stroke width.
Exercise
You draw an open path shaped like a "V" with strokeWidth 20 and the default Paint settings except style = PaintingStyle.stroke. The bottom point of the V is a long thin spike. Which Paint property should you change to get a rounded bottom, and what happens to the two open ends of the V when you do?
Show answer
Set strokeJoin = StrokeJoin.round. The join only affects the corner at the bottom of the V, so the two open ends keep their default butt caps and stay flat. To round the ends as well, also set strokeCap = StrokeCap.round, which extends each end by half the stroke width (10 pixels).
Exercise
A circular progress arc has strokeWidth 16 and is drawn with Rect.fromLTWH(0, 0, 200, 200) on a 200 by 200 canvas. The outer edge looks cut off on all sides. What is the fix, and how many pixels of the stroke were being clipped on each side?
Show answer
Half the stroke width, 8 pixels, was outside the canvas on each side. Deflate the rectangle by 8 (for example rect.deflate(8)) before passing it to drawArc, so the whole stroke fits inside the 200 by 200 area.