【Flutter】CustomPainterで図形を描く

概要

Flutterで図形を描く際に使用する

CustomPainter の使用方法のまとめ。

開発環境

OS Windows11
Editor VS Code
Flutter Ver. 3.0.5

CustomPaintウィジェットを作成する

図形を描画する際は、CustomPaintウィジェットを使用する。

CustomPaintウィジェットの実装方法は以下に記載。

CustomPainterクラスを作成

CustomPaintウィジェットを作成する際はまず、 CustomPainter を継承したクラスを作成する。

以下の用に作成し、図形を描画する際はpaintメソッドに書いていく。

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
        //... ここに図形をコード書く
  }

    // trueの場合、再描画を行う
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

CustomPaintウィジェットを作成

CustomPainter を継承したクラスを作成したら 、CustomPaint ウィジェットを以下のように実装する。

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    return Scaffold(
        body: SafeArea(
      child: CustomPaint(
        painter: MyPainter(),
        size: size,
      ),
    ));
  }
}

図形の描き方

四角形を描く

四角形を描く際は、 drawRectを使用する。

void paint(Canvas canvas, Size size) {
    const rSize = Size(200, 200);
    final center = Offset((size.width / 2) - (rSize.width / 2),
        (size.height / 2) - (rSize.width / 2));
    canvas.drawRect(center & rSize, Paint()..color = const Color(0xFF3f51b5));
  }

円を描く

円を描く際は、 drawCircleを使用する。

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

線を描く

線を描く際は、 drawLineを使用する。

void paint(Canvas canvas, Size size) {
    canvas.drawLine(
        const Offset(0, 0),
        Offset(size.width, size.height),
        Paint()
          ..color = const Color(0xFF3f51b5)
          ..strokeWidth = 5);
  }

参考

CustomPaint class - widgets library - Dart API

CustomPainter class - rendering library - Dart API

Canvas class - dart:ui library - Dart API