CustomPaint
使用实例和代码:
1.canvas.drawColor 绘制背景颜色
class MyPainter1 extends CustomPainter {
void paint(Canvas canvas, Size size) {
//绘制背景颜色,整个UI 现在就是红色的
canvas.drawColor(Colors.red, BlendMode.srcATop);
}
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
2.canvas.drawCircle 绘制圆
final whitePaint = Paint()..color = Colors.red;
//offset 位置,半径
canvas.drawCircle(const Offset(100, 100), 100, whitePaint);
3.canvas.drawRect绘四边形
//绘制四边形
final redPaint = Paint()..color = Colors.red;
// left:距离左边的距离, top:距离右边的距离, width, height
canvas.drawRect(Rect.fromLTWH(100, 100, 100, 100), redPaint);
//center 中心点的位置, 宽高,
canvas.drawRect(
Rect.fromCenter(center: Offset(50, 50), width: 100, height: 100),
redPaint);
//radius 半径
canvas.drawRect(
Rect.fromCircle(center: const Offset(50, 50), radius: 50), redPaint);
canvas.drawRect(
Rect.fromPoints(const Offset(50, 50), Offset(100, 100)), redPaint);
4.canvas.drawRRect 绘制圆角矩形
其他的方法可以自行尝试,参数大同小异
// left, top, right, bottom, radius
canvas.drawRRect(
RRect.fromLTRBR(100, 100, 200, 200, Radius.circular(20)), redPaint);
//可以设定不同边角弧度的
canvas.drawRRect(
RRect.fromLTRBAndCorners(100, 100, 200, 200,
topLeft: const Radius.circular(20)),
redPaint);
5.canvas.drawRRect 嵌套绘制
canvas.drawDRRect(
RRect.fromLTRBR(100, 100, 300, 300, const Radius.circular(20)),
RRect.fromLTRBR(150, 150, 200, 200, const Radius.circular(20)),
redPaint);
6.canvas.drawOval 绘制椭圆形
//椭圆形
canvas.drawOval(Rect.fromLTRB(100, 80, 400, 300), redPaint);
7.canvas.drawPath 绘制路径
final redPaint = Paint()
..color = Colors.red
..strokeWidth = 2.0
..style = PaintingStyle.stroke;
// final path = Path()
// ..moveTo(100, 100) //起始点
// ..lineTo(200, 200) //链接到点
// ..lineTo(400, 400) //链接到点
// ..close(); //关闭
// canvas.drawPath(path, redPaint);
final path1 = Path()
..moveTo(400, 400) //起始点
..lineTo(400, 500) //链接到点
..lineTo(400, 400) //链接到点
..addRect(Rect.fromLTRB(500, 500, 100, 100)) //新增一个矩形,或者其他的也可以
..close(); //关闭
//或者在这边添加也可以
// path1.addRect(Rect.fromLTRB(500, 500, 100, 100));
// path1.close();
canvas.drawPath(path1, redPaint);