flutter绘制半圆和绘制其他图形
在Flutter中,绘制半圆可以使用CustomPainter
和Canvas
类。以下是绘制半圆的示例代码:
class SemiCirclePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..color = Colors.blue
..style = PaintingStyle.fill;
Rect rect = Rect.fromLTWH(0, 0, size.width, size.height / 2);
canvas.drawArc(rect, -math.pi, math.pi, true, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SizedBox(
width: 100,
height: 100,
child: CustomPaint(
painter: SemiCirclePainter(),
),
);
}
}
在这个示例中,SemiCirclePainter
类继承自CustomPainter
,并在paint
方法中使用Canvas
的drawArc
方法绘制一个半圆。MyWidget
是一个使用了CustomPaint
控件的无状态小部件,以便显示绘制的半圆。
绘制其他形状(如三角形、多边形等)时,可以使用Path
类来创建自定义形状,并使用Canvas
的drawPath
方法来绘制。以下是一个绘制三角形的示例:
class TrianglePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..color = Colors.red
..style = PaintingStyle.fill;
Path path = Path();
path.moveTo(size.width / 2, 0);
path.lineTo(0, size.height);
path.lineTo(size.width, size.height);
path.close();
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SizedBox(
width: 100,
height: 100,
child: CustomPaint(
painter: TrianglePainter(),
),
);
}
}
在这个示例中,TrianglePainter
类创建了一个三角形,并使用drawPath
方法将其绘制出来。MyWidget
小部件同样使用CustomPaint
控件来展示绘制的三角形。
评论已关闭