In this section, we will explore how to create custom graphics in Flutter using the CustomPaint widget and the Canvas class. This is an advanced topic that allows you to draw directly on the screen, giving you the flexibility to create complex and unique UI elements.

Key Concepts

  1. CustomPaint Widget: A widget that provides a canvas on which to draw during the paint phase.
  2. CustomPainter Class: A class that you extend to define your custom painting logic.
  3. Canvas Class: Provides methods to draw shapes, text, images, and more.
  4. Paint Class: Defines the style and color properties used when drawing on the canvas.

CustomPaint Widget

The CustomPaint widget is used to create a drawing area. It takes a painter property, which is an instance of a class that extends CustomPainter.

Example

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Custom Paint Example')),
        body: Center(
          child: CustomPaint(
            size: Size(300, 300),
            painter: MyPainter(),
          ),
        ),
      ),
    );
  }
}

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

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

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

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

Explanation

  • CustomPaint: The widget that provides a canvas for drawing.
  • MyPainter: A class that extends CustomPainter and overrides the paint method to define the drawing logic.
  • paint: The method where you define what to draw on the canvas.
  • shouldRepaint: Determines whether the custom painter should repaint. In this simple example, it returns false.

Drawing with Canvas

The Canvas class provides various methods to draw shapes, text, images, and more.

Drawing Shapes

Drawing a Circle

canvas.drawCircle(center, radius, paint);

Drawing a Rectangle

final rect = Rect.fromLTWH(50, 50, 200, 100);
canvas.drawRect(rect, paint);

Drawing a Line

final start = Offset(0, 0);
final end = Offset(size.width, size.height);
canvas.drawLine(start, end, paint);

Drawing Text

final textPainter = TextPainter(
  text: TextSpan(
    text: 'Hello, Canvas!',
    style: TextStyle(color: Colors.black, fontSize: 24),
  ),
  textDirection: TextDirection.ltr,
);

textPainter.layout(minWidth: 0, maxWidth: size.width);
final offset = Offset(50, 50);
textPainter.paint(canvas, offset);

Practical Exercise

Task

Create a custom painter that draws a house with a rectangle for the base and a triangle for the roof.

Solution

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Custom Paint Exercise')),
        body: Center(
          child: CustomPaint(
            size: Size(300, 300),
            painter: HousePainter(),
          ),
        ),
      ),
    );
  }
}

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

    // Draw the base of the house
    final base = Rect.fromLTWH(50, 150, 200, 100);
    canvas.drawRect(base, paint);

    // Draw the roof of the house
    final path = Path()
      ..moveTo(50, 150)
      ..lineTo(150, 50)
      ..lineTo(250, 150)
      ..close();

    paint.color = Colors.red;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

Explanation

  • HousePainter: A custom painter that draws a house.
  • paint: Draws a rectangle for the base and a triangle for the roof using a Path.

Summary

In this section, you learned how to use the CustomPaint widget and the Canvas class to create custom graphics in Flutter. You explored various methods provided by the Canvas class to draw shapes and text. Finally, you completed a practical exercise to reinforce your understanding.

Next, we will delve into more advanced topics in Flutter, such as platform channels and performance optimization.

Flutter Development Course

Module 1: Introduction to Flutter

Module 2: Dart Programming Basics

Module 3: Flutter Widgets

Module 4: State Management

Module 5: Navigation and Routing

Module 6: Networking and APIs

Module 7: Persistence and Storage

Module 8: Advanced Flutter Concepts

Module 9: Testing and Debugging

Module 10: Deployment and Maintenance

Module 11: Flutter for Web and Desktop

© Copyright 2024. All rights reserved