0Pricing
Flutter Mobile Development · 강의

Canvas API: 경로, 페인트 및 셰이더

Canvas 기본 요소와 Paint 설정을 사용해 도형, 그라데이션 및 선을 그립니다.

Canvas API: 경로, 페인트 및 셰이더은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Meet the Canvas

When you build a CustomPainter, Flutter hands you two things in paint(): a Canvas and a Size.

  • Canvas is your drawing surface. It exposes primitives like drawRect, drawCircle, drawPath, and drawLine.
  • Size tells you how big the area is, so you can scale your drawing to fit any device.

Every draw call needs a Paint object that describes how to draw: color, stroke vs fill, width, and more.

void paint(Canvas canvas, Size size) {
  final paint = Paint()..color = const Color(0xFF2196F3);
  canvas.drawRect(
    Rect.fromLTWH(0, 0, size.width, size.height),
    paint,
  );
}

The Paint Object

A Paint is a bundle of styling options. The most important fields are:

  • color — the color used to draw.
  • style — PaintingStyle.fill (solid interior) or PaintingStyle.stroke (outline only).
  • strokeWidth — line thickness when stroking.
  • isAntiAlias — smooth edges, on by default.

Flutter idiom uses the cascade operator .. to configure a freshly created Paint in one expression.

final fill = Paint()
  ..color = const Color(0xFFE91E63)
  ..style = PaintingStyle.fill;

final outline = Paint()
  ..color = const Color(0xFF000000)
  ..style = PaintingStyle.stroke
  ..strokeWidth = 4.0;

Drawing Basic Shapes

The Canvas offers ready-made primitives so you do not always need a path:

  • drawRect(Rect, Paint) — axis-aligned rectangle.
  • drawRRect(RRect, Paint) — rounded rectangle.
  • drawCircle(Offset center, double radius, Paint)
  • drawOval(Rect, Paint) — fills the bounding rect with an ellipse.

Coordinates start at (0,0) in the top-left corner; x grows right, y grows down.

void paint(Canvas canvas, Size size) {
  final p = Paint()..color = const Color(0xFF4CAF50);
  final center = Offset(size.width / 2, size.height / 2);

  canvas.drawCircle(center, 40, p);
  canvas.drawRRect(
    RRect.fromRectAndRadius(
      Rect.fromLTWH(10, 10, 80, 50),
      const Radius.circular(12),
    ),
    p,
  );
}

Strokes: Caps, Joins, and Width

When style is PaintingStyle.stroke, several properties shape the line:

  • strokeWidth — thickness in logical pixels.
  • strokeCap — how line ends look: butt, round, or square.
  • strokeJoin — how corners connect: miter, round, or bevel.

Round caps and joins are common for friendly, smooth chart and signature drawing.

final stroke = Paint()
  ..color = const Color(0xFF9C27B0)
  ..style = PaintingStyle.stroke
  ..strokeWidth = 6.0
  ..strokeCap = StrokeCap.round
  ..strokeJoin = StrokeJoin.round;

// canvas.drawLine(Offset(10, 10), Offset(120, 60), stroke);

Building a Path

A Path describes an arbitrary outline made of line and curve segments. The core methods are:

  • moveTo(x, y) — lift the pen and start a new subpath.
  • lineTo(x, y) — draw a straight segment.
  • quadraticBezierTo / cubicTo — curved segments.
  • close() — connect back to the subpath start.

Draw the finished path with canvas.drawPath(path, paint).

void paint(Canvas canvas, Size size) {
  final path = Path()
    ..moveTo(size.width / 2, 0)
    ..lineTo(size.width, size.height)
    ..lineTo(0, size.height)
    ..close();

  final paint = Paint()..color = const Color(0xFFFF5722);
  canvas.drawPath(path, paint);
}

Curves with Bezier Segments

Smooth shapes come from Bezier curves. The most common is the quadratic Bezier, which uses one control point.

  • quadraticBezierTo(cpx, cpy, x, y) bends the line toward the control point (cpx, cpy) on its way to the end point (x, y).
  • cubicTo(c1x, c1y, c2x, c2y, x, y) uses two control points for S-curves.

These power wave dividers, chart lines, and speech-bubble tails.

void paint(Canvas canvas, Size size) {
  final wave = Path()
    ..moveTo(0, size.height * 0.5)
    ..quadraticBezierTo(
      size.width * 0.25, size.height * 0.2,
      size.width * 0.5, size.height * 0.5,
    )
    ..quadraticBezierTo(
      size.width * 0.75, size.height * 0.8,
      size.width, size.height * 0.5,
    );

  final paint = Paint()
    ..color = const Color(0xFF00BCD4)
    ..style = PaintingStyle.stroke
    ..strokeWidth = 3;
  canvas.drawPath(wave, paint);
}

Plain Dart: Computing Points

Canvas math is just geometry. Before you draw, you often compute coordinates with plain Dart. Here we generate evenly spaced points along a sine wave — the same values you would feed into path.lineTo.

This logic is framework-free, so you can unit-test it without rendering anything.

import 'dart:math';

List<Point<double>> wavePoints(double width, double height, int n) {
  final pts = <Point<double>>[];
  for (var i = 0; i <= n; i++) {
    final x = width * i / n;
    final y = height / 2 + sin(i / n * 2 * pi) * height / 4;
    pts.add(Point(x, y));
  }
  return pts;
}

void main() {
  final pts = wavePoints(200, 100, 4);
  for (final p in pts) {
    print('(${p.x.toStringAsFixed(1)}, ${p.y.toStringAsFixed(1)})');
  }
}

Shaders: Linear Gradients

A shader fills a shape with more than a flat color. The most common is a linear gradient. You build it with ui.Gradient.linear and assign it to paint.shader.

  • from / to are the start and end Offsets of the gradient line.
  • colors lists the gradient stops, blended along that line.

Once shader is set, the paint's color is ignored for fills.

import 'dart:ui' as ui;

Paint gradientPaint(Size size) {
  return Paint()
    ..shader = ui.Gradient.linear(
      Offset.zero,
      Offset(size.width, size.height),
      const [Color(0xFF2196F3), Color(0xFF9C27B0)],
    );
}

Radial and Sweep Gradients

Beyond linear, Flutter offers two more gradient shaders:

  • Radial — ui.Gradient.radial(center, radius, colors) blends outward from a center point, great for glows and spotlights.
  • Sweep — ui.Gradient.sweep(center, colors) rotates colors around a center, ideal for circular progress and color wheels.

You can add an optional stops list (0.0 to 1.0) to control exactly where each color sits.

import 'dart:ui' as ui;

Paint glow(Offset center) {
  return Paint()
    ..shader = ui.Gradient.radial(
      center,
      60,
      const [Color(0xFFFFEB3B), Color(0x00FFEB3B)],
      const [0.0, 1.0],
    );
}

Putting It Together in a Painter

A real CustomPainter combines paths, paints, and shaders. Remember two overrides:

  • paint(canvas, size) — do the drawing.
  • shouldRepaint(old) — return true only when inputs changed, so Flutter avoids needless repaints.

This snippet draws a gradient-filled rounded card with a stroked border.

class CardPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final rect = Rect.fromLTWH(0, 0, size.width, size.height);
    final rrect = RRect.fromRectAndRadius(rect, const Radius.circular(16));

    final fill = Paint()
      ..shader = ui.Gradient.linear(
        rect.topLeft, rect.bottomRight,
        const [Color(0xFF42A5F5), Color(0xFF7E57C2)],
      );
    canvas.drawRRect(rrect, fill);

    final border = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2
      ..color = const Color(0x33000000);
    canvas.drawRRect(rrect, border);
  }

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

Save, Restore, and Transforms

The Canvas keeps a stack of transforms and clips. Use it to draw rotated or scaled content without permanently changing state:

  • canvas.save() pushes the current matrix.
  • canvas.translate / rotate / scale modify it.
  • canvas.restore() pops back to where you were.

Always pair every save() with a restore(), or later draws will inherit the transform.

void paint(Canvas canvas, Size size) {
  final p = Paint()..color = const Color(0xFF3F51B5);
  canvas.save();
  canvas.translate(size.width / 2, size.height / 2);
  canvas.rotate(0.785398); // 45 degrees in radians
  canvas.drawRect(
    const Rect.fromLTWH(-30, -30, 60, 60),
    p,
  );
  canvas.restore();
}

Quick Check

Test your understanding of the Paint configuration.

Recap

You now command the Canvas API:

  • Paint controls how you draw: color, style (fill vs stroke), strokeWidth, caps, and joins.
  • Primitives like drawRect, drawRRect, and drawCircle handle common shapes; Path with moveTo, lineTo, and Bezier curves handles anything custom.
  • Shaders (Gradient.linear, radial, sweep) fill or stroke with gradients and override the flat color.
  • save/restore isolates transforms, and shouldRepaint keeps rendering efficient.

With these building blocks you can draw charts, custom controls, and rich decorations entirely in Dart.

자주 묻는 질문

“Canvas API: 경로, 페인트 및 셰이더” 강의는 무료인가요?

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

“Canvas API: 경로, 페인트 및 셰이더”에서 뭘 배우나요?

Canvas 기본 요소와 Paint 설정을 사용해 도형, 그라데이션 및 선을 그립니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“Canvas API: 경로, 페인트 및 셰이더” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. Canvas API: 경로, 페인트 및 셰이더
  2. 대화형 사용자 지정 차트 위젯 만들기
  3. 클리핑, 혼합 모드 및 레이어 합성
  4. 히트 테스트 및 다시 그리기 최적화
← Flutter Mobile Development(으)로 돌아가기