Flutter学习:使用CustomPaint绘制路径
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('CustomPaint 示例'),
),
body: Center(
child: CustomPaint(
size: Size(200, 200),
painter: MyPainter(),
),
),
),
);
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.stroke
..strokeWidth = 3.0;
final path = Path();
path.moveTo(size.width / 2, 0.0); // 移动到画布中心的起始点
path.lineTo(0.0, size.height); // 绘制一条水平线到画布底部的左侧
path.lineTo(size.width, size.height); // 绘制一条水平线到画布底部的右侧
path.close(); // 关闭路径形成一个三角形
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false; // 自定义的绘制不需要重绘时返回false
}
}
这段代码创建了一个简单的Flutter应用,使用CustomPaint
控件和MyPainter
自定义绘制类来绘制一个等腰直角三角形。MyPainter
类覆盖了paint
方法来定义如何绘制路径,并通过shouldRepaint
方法指出是否需要重新绘制。这个例子展示了如何使用Flutter的绘图API进行自定义绘制。
评论已关闭