
import 'package:flutter/material.dart';
class AppleWatchScreen extends StatefulWidget {
const AppleWatchScreen({super.key});
State<AppleWatchScreen> createState() => _AppleWatchScreenState();
}
class _AppleWatchScreenState extends State<AppleWatchScreen> {
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.black,
foregroundColor: Colors.white,
title: const Text("Apple Watch"),
),
body: Center(
child: CustomPaint(
painter: AppleWatchPainter(),
size: const Size(400, 400),
),
),
);
}
}
class AppleWatchPainter extends CustomPainter {
void paint(Canvas canvas, Size size) {
final rect = Rect.fromLTWH(
0,
0,
size.width,
size.height,
);
final paint = Paint()..color = Colors.blue;
canvas.drawRect(rect, paint);
final circlePaint = Paint()
..color = Colors.red
..style = PaintingStyle.stroke
..strokeWidth = 20;
canvas.drawCircle(
Offset(size.width / 2, size.width / 2),
size.width / 2,
circlePaint,
);
}
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}
이 예제는 Flutter에서 사용자 정의 그래픽을 그리기 위해 CustomPainter를 사용하는 방법을 보여줍니다. 코드를 더 자세히 살펴보면서 단계별로 설명하겠습니다.
AppleWatchScreen 위젯: 화면 구성먼저, AppleWatchScreen이라는 위젯을 만듭니다. 이 위젯은 앱에서 사용자에게 보여지는 화면을 담당합니다.
Scaffold를 사용하여 기본적인 앱 레이아웃을 구성합니다. 여기에는 앱 바(AppBar)와 바디(Body)가 포함됩니다.backgroundColor 속성을 Colors.black으로 설정하여 배경색을 검은색으로 만듭니다. 이는 Apple Watch의 외형을 모방하기 위함입니다.Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.black,
title: const Text("Apple Watch"),
),
...
)
CustomPaint 위젯: 그리기 영역 설정화면의 중앙에 사용자 정의 그래픽을 그리기 위해 CustomPaint 위젯을 사용합니다. CustomPaint는 painter라는 속성을 통해 그리기 로직이 정의된 CustomPainter 객체를 받습니다.
CustomPaint의 size 속성으로 그리기 영역의 크기를 설정합니다. 여기서는 400x400으로 설정했습니다. 이 영역 안에서 그래픽을 그릴 것입니다.CustomPaint(
painter: AppleWatchPainter(),
size: const Size(400, 400),
)
AppleWatchPainter 클래스: 사용자 정의 그래픽 그리기AppleWatchPainter는 CustomPainter를 상속받은 클래스로, 실제로 캔버스에 그림을 그리는 로직을 담고 있습니다.
paint 메서드는 그림을 그리는 데 사용됩니다. Canvas 객체와 Size 객체가 인자로 전달됩니다. Canvas는 그림을 그릴 캔버스를 나타내고, Size는 그리기 영역의 크기를 나타냅니다.Rect.fromLTWH로 사각형의 위치와 크기를 정의합니다. 여기서 (0, 0)은 왼쪽 상단 모서리의 위치이고, size.width와 size.height로 사각형의 너비와 높이를 설정합니다.Paint 객체를 생성하고, color 속성을 Colors.blue로 설정하여 사각형의 색상을 파란색으로 지정합니다.canvas.drawRect 메서드로 캔버스에 사각형을 그립니다.Paint 객체를 다시 생성하고, 여러 속성(color, style, strokeWidth)을 설정하여 원의 외곽선을 정의합니다.canvas.drawCircle 메서드로 캔버스에 원을 그립니다. 원의 중심은 (size.width / 2, size.width / 2)로 설정하고, 반지름은 size.width / 2로 설정하여 캔버스의 중앙에 원을 그립니다.final circlePaint = Paint()
..color = Colors.red
..style = PaintingStyle.stroke
..strokeWidth = 20;
canvas.drawCircle(
Offset(size.width / 2, size.width / 2),
size.width / 2,
circlePaint,
);
shouldRepaint 메서드: 다시 그리기 결정shouldRepaint 메서드는 캔버스를 다시 그릴 필요가 있는지 결정합니다. 여기서는 항상 false를 반환하여, 위젯이 다시 그릴 필요가 없음을 나타냅니다. 그래픽이 변하지 않기 때문에, 한 번 그려진 후에는 다시 그릴 필요가 없습니다.이 예제를 통해, Flutter에서 CustomPainter를 사용하여 복잡한 사용자 정의 그래픽을 캔버스에 그릴 수 있는 방법을 배울 수 있습니다. paint 메서드 내에서는 다양한 그리기 메서드(drawRect, drawCircle 등)를 사용하여 원하는 그래픽을 자유롭게 표현할 수 있습니다.