0Pricing
Flutter Mobile Development · 강의

CustomPainter 및 Canvas

`CustomPainter`와 `Canvas` API를 사용한 사용자 지정 그리기를 익혀 고유한 도형, 그래프 및 시각 효과를 만듭니다.

CustomPainter 및 Canvas은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 및 Canvas” 강의는 무료인가요?

네 — “CustomPainter 및 Canvas” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“CustomPainter 및 Canvas”에서 뭘 배우나요?

`CustomPainter`와 `Canvas` API를 사용한 사용자 지정 그리기를 익혀 고유한 도형, 그래프 및 시각 효과를 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“CustomPainter 및 Canvas” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. CustomPainter 및 Canvas
  2. 암시적 애니메이션
  3. 명시적 애니메이션 및 Hero
  4. 엇갈린 애니메이션과 물리 기반 애니메이션
← Flutter Mobile Development(으)로 돌아가기