Canvas and Paint
- Flutter course
- Advanced
- Lesson 53/69
- 4 min
Draw lines, circles and rects with Canvas and Paint.
Canvas and Paint
Canvas is the surface you draw on; Paint is the brush that holds properties like color and stroke width. To draw a circle, you pass a center point, a radius, and a Paint to canvas.drawCircle.
final paint = Paint()
..color = Colors.red
..style = PaintingStyle.fill;
canvas.drawCircle(Offset(50, 50), 40, paint);Paint styles
The style property of Paint fills with PaintingStyle.fill and draws only the border with PaintingStyle.stroke. strokeWidth sets the border thickness. You can use multiple Paints on the same canvas.
final border = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 3;
canvas.drawRect(rect, border);Practice Draw a red filled circle
Write the paint method in CirclePainter. Draw a red filled circle (center 50,50, radius 30). In main, take an instance and print its type.
Starter code
import 'package:flutter/material.dart';
// CirclePainter sınıfını tanımla
void main() {
// CirclePainter örneğini al ve tipini yazdır
}Sample solution
import 'package:flutter/material.dart';
class CirclePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.red
..style = PaintingStyle.fill;
canvas.drawCircle(const Offset(50, 50), 30, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
void main() {
final painter = CirclePainter();
print(painter.runtimeType);
}Expected output
CirclePainter
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following is a valid drawCircle call?
- canvas.drawCircle(Colors.red, 40, paint)
- canvas.drawCircle(40, Offset(50, 50), paint)
- canvas.drawCircle(Offset(50, 50), 40, paint) Correct answer
- canvas.drawCircle(paint, Offset(50, 50), 40)
Explanation: The drawCircle signature is drawCircle(Offset c, double radius, Paint paint); first the center, then the radius, and finally the Paint.
2 Pass Paint to drawCircle
canvas.drawCircle(Offset(50, 50), 40, ____);
canvas.drawCircle(Offset(50, 50), 40, paint);
Explanation: drawCircle expects a Paint object as its third parameter; a Color cannot be passed directly.
3 Canvas and Paint matches
| Term | Meaning |
|---|---|
Canvas |
Drawing surface |
Paint |
Brush properties |
drawCircle |
Draws a circle |
PaintingStyle.fill |
Filled style |