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 {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.black
..strokeWidth = 2.0
..strokeCap = StrokeCap.round;
final startPoint = Offset(size.width / 4, size.height / 4);
final endPoint = Offset(size.width * 3 / 4, size.height * 3 / 4);
canvas.drawLine(startPoint, endPoint, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
在这个例子中,我们创建了一个自定义的CustomPainter,它在一个200x200像素的画布上绘制了一条从左上角到右下角的黑色直线。直线的粗细为2.0,并且两端有圆形头。
shouldRepaint
方法返回false表示当这个CustomPainter不需要重新绘制时,Flutter不会调用paint
方法,这有助于性能优化。如果你的画笔会变化,你应该在某些条件改变时返回true,这样画笔就会重新绘制。
评论已关闭