Flutter 画笔(Paint)、绘制直线(drawLine)
在Flutter中,要使用CustomPainter
来绘制直线,你需要实现paint
方法来描绘你的直线。以下是一个简单的例子,展示了如何在Flutter中使用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(0, size.height / 2);
final endPoint = Offset(size.width, size.height / 2);
canvas.drawLine(startPoint, endPoint, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
在这个例子中,我们创建了一个LinePainter
类,它扩展了CustomPainter
并实现了paint
方法。在paint
方法中,我们创建了一个Paint
对象来设置直线的颜色、宽度和样式,然后我们定义了直线的起点和终点,并使用drawLine
方法来绘制这条直线。shouldRepaint
方法返回false
表示当widget重新构建时,不需要重新绘制画布。
评论已关闭