0Pricing
Flutter Mobile Development · 课时

CustomPainter 与画布

深入学习使用 `CustomPainter` 和 `Canvas` API 进行自定义绘图,创建独特的形状、图表和视觉效果。

CustomPainter 与画布 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flutter Mobile Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flutter Mobile Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to Custom Drawing

Flutter's widgets are powerful, but sometimes you need to draw something truly unique. Think custom graphs, unique shapes, or special visual effects!

This is where custom drawing comes in. It gives you pixel-level control over what appears on the screen, letting you create anything imaginable.

Meet CustomPainter

At the heart of custom drawing in Flutter is the CustomPainter class. You extend this class to define what and how to draw.

  • It provides a canvas to draw on.
  • It requires you to implement two key methods: paint and shouldRepaint.

The Canvas: Your Drawing Board

The paint method receives a Canvas object. Think of the Canvas as your blank drawing board, ready for your artistic commands.

It uses a 2D Cartesian coordinate system: the top-left corner is (0,0). X-values increase to the right, and Y-values increase downwards.

Styling with Paint

Before you draw, you need to tell Flutter how to draw. This is done using a Paint object. The Paint object defines properties like:

  • Color: What color should the drawing be?
  • StrokeWidth: How thick should lines be?
  • Style: Should it be filled (PaintingStyle.fill) or just an outline (PaintingStyle.stroke)?

Drawing Basic Shapes: Line

Let's draw our first shape: a simple line! We use canvas.drawLine(), providing start and end points (Offset) and our Paint style.

Try running this example:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Draw Line')),
        body: Center(
          child: CustomPaint(
            painter: LinePainter(),
            child: Container(),
          ),
        ),
      ),
    );
  }
}

class LinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..strokeWidth = 4.0
      ..style = PaintingStyle.stroke;

    final p1 = Offset(0, size.height / 2);
    final p2 = Offset(size.width, size.height / 2);

    canvas.drawLine(p1, p2, paint);
  }

  @override
  bool shouldRepaint(covariant LinePainter oldDelegate) => false;
}

Drawing Basic Shapes: Circle

Drawing a circle is just as easy with canvas.drawCircle(). You need a center point, a radius, and a Paint object.

Notice how we use size.width / 2 and size.height / 2 to center our drawings.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Draw Circle')),
        body: Center(
          child: CustomPaint(
            painter: CirclePainter(),
            child: Container(),
          ),
        ),
      ),
    );
  }
}

class CirclePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.red
      ..strokeWidth = 5.0
      ..style = PaintingStyle.fill;

    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 4;

    canvas.drawCircle(center, radius, paint);
  }

  @override
  bool shouldRepaint(covariant CirclePainter oldDelegate) => false;
}

Drawing Basic Shapes: Rectangle

To draw a rectangle, we use canvas.drawRect(). This method takes a Rect object, which defines the rectangle's position and size.

A Rect.fromLTWH constructor is useful for defining a rectangle from its left, top, width, and height.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Draw Rectangle')),
        body: Center(
          child: CustomPaint(
            painter: RectanglePainter(),
            child: Container(),
          ),
        ),
      ),
    );
  }
}

class RectanglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.green
      ..strokeWidth = 3.0
      ..style = PaintingStyle.stroke;

    final rect = Rect.fromLTWH(size.width * 0.2, size.height * 0.2, size.width * 0.6, size.height * 0.6);

    canvas.drawRect(rect, paint);
  }

  @override
  bool shouldRepaint(covariant RectanglePainter oldDelegate) => false;
}

The shouldRepaint Method

The shouldRepaint method in CustomPainter is crucial for performance. It tells Flutter whether your custom painting needs to be redrawn.

  • Return true if the new delegate (the updated painter) has different data that would change the drawing.
  • Return false if the drawing would be identical. This prevents unnecessary repaints and saves CPU cycles.

For static drawings, false is often sufficient.

Drawing Complex Shapes with Path

For more complex or irregular shapes, you'll use a Path object. A Path allows you to define a series of connected lines and curves.

You can move to a point (moveTo), draw lines to points (lineTo), and finally close the path (close) before drawing it with canvas.drawPath().

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Draw Triangle')),
        body: Center(
          child: CustomPaint(
            painter: TrianglePainter(),
            child: Container(),
          ),
        ),
      ),
    );
  }
}

class TrianglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.purple
      ..style = PaintingStyle.fill;

    final path = Path();
    path.moveTo(size.width / 2, size.height * 0.1);
    path.lineTo(size.width * 0.9, size.height * 0.9);
    path.lineTo(size.width * 0.1, size.height * 0.9);
    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant TrianglePainter oldDelegate) => false;
}

Test Your Knowledge!

Which of the following statements about Flutter's custom drawing is TRUE?

Recap: Custom Drawing Basics

You've taken your first steps into custom drawing in Flutter! You learned:

  • CustomPainter is your entry point for custom visuals.
  • The Canvas object is your drawing surface with a top-left origin.
  • The Paint object defines the style (color, stroke, fill).
  • How to draw basic shapes like lines, circles, and rectangles.
  • shouldRepaint helps optimize performance.
  • Path allows for drawing complex, custom shapes.

Keep experimenting to bring your unique designs to life!

常见问题解答

「CustomPainter 与画布」课时是免费的吗?

是的 — 「CustomPainter 与画布」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。

「CustomPainter 与画布」这节课中我会学到什么?

深入学习使用 `CustomPainter` 和 `Canvas` API 进行自定义绘图,创建独特的形状、图表和视觉效果。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Flutter Mobile Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「CustomPainter 与画布」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Flutter Mobile Development 课中编写并运行代码吗?

能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. CustomPainter 与画布
  2. 隐式动画
  3. 显式动画与共享元素
  4. 交错动画与基于物理的动画
← 返回 Flutter Mobile Development