Flutter 画笔(Paint)、绘制直线(drawLine)
在Flutter中,我们可以使用CustomPainter来自定义绘制。下面是一个使用CustomPainter来绘制直线的例子:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: CustomPaint(
size: Size(200, 200),
painter: LinePainter(),
),
),
),
);
}
}
class LinePainter extends CustomPainter {
Paint _paint = Paint()
..color = Colors.blue
..strokeWidth = 2.0
..strokeCap = StrokeCap.round;
@override
void paint(Canvas canvas, Size size) {
// 绘制一条从(0, 0)到(size.width, size.height)的直线
canvas.drawLine(Offset(0, 0), Offset(size.width, size.height), _paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
在这个例子中,我们创建了一个自定义的CustomPainter,它在画布上绘制了一条从左上角到右下角的蓝色直线。我们设置了画笔的颜色、粗细和形状。shouldRepaint
方法返回false表示当widget重新绘制时,不会再次调用paint
方法,除非我们返回true。这样做可以提高绘制性能。
评论已关闭