有時候我們需要在螢幕上繪圖,可以想像有著各式各樣畫筆、顏色、粗細等工具,此時我們可以怎麼做呢?🤔
可以使用 CustomPaint Widget,讓我們在畫布上隨意繪圖。
先來秀出我們最後的成果:
可以見到螢幕上有個黃色正方形,裡頭又有個綠色三角形。
首先來看一下完整的原始碼:
/*
Author: HappyMan
Date: 2022/02/14
Topic: CustomPaint Class
*/
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Happy Drawing Triangle'),
),
body: Center(
child: Container(
color: Colors.yellow,
child: CustomPaint(size: Size(300, 300), painter: DrawTriangle()),
),
),
),
);
}
}
class DrawTriangle extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var path = Path();
path.moveTo(size.width / 2, Random().nextDouble() * (size.height / 2));
path.lineTo(0, size.height);
path.lineTo(size.height, size.width);
path.close();
canvas.drawPath(path, Paint()..color = Color(Random().nextInt(0xffffffff)).withAlpha(0xff));
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
我在 Container 裡放了 CustomPaint,然後透過 Canvas 繪製 Path。
在 CustomPainter 擴展中必須實作兩個 Function:
- void paint(Canvas canvas, Size size)
- bool shouldRepaint(CustomPainter oldDelegate)
實際跑專案,在 Web 拖曳視窗大小,會改變顏色與三角點的位置;抑或是在 iOS 橫放或直放切換也會改變顏色與三角點的位置。
這裡是透過亂數也決定三角點的位置和改變顏色。
參考:
CustomPaint (Flutter Widget of the Week)
隨意留個言吧:)~