如何在Flutter中实现指定样式的弧形自定义设计?
Flutter 实现自定义弧形设计的解决方案
核心思路
放弃单纯依赖drawArc(仅适配正圆弧场景),改用**贝塞尔曲线+Path**精准控制弧形形状,匹配设计图的非正圆弧需求。
代码实现
1. 自定义Painter类
class ArcCustomPainter extends CustomPainter { final Color fillColor; final double arcHeight; // 控制弧形凹/凸的高度 ArcCustomPainter({required this.fillColor, required this.arcHeight}); @override void paint(Canvas canvas, Size size) { final paint = Paint()..color = fillColor; final path = Path(); // 构建路径:左上→左部顶部→贝塞尔弧形→右部顶部→右上→右下→左下→闭合 path.moveTo(0, 0); path.lineTo(size.width * 0.25, 0); // 二次贝塞尔曲线:控制点在顶部中心,控制弧形弧度 path.quadraticBezierTo( size.width / 2, arcHeight, // 正数=向下凹,负数=向上凸 size.width * 0.75, 0, ); path.lineTo(size.width, 0); path.lineTo(size.width, size.height); path.lineTo(0, size.height); path.close(); canvas.drawPath(path, paint); } @override bool shouldRepaint(covariant ArcCustomPainter oldDelegate) { return oldDelegate.fillColor != fillColor || oldDelegate.arcHeight != arcHeight; } }
2. 封装成可复用Widget
class ArcContainer extends StatelessWidget { final Widget child; final Color backgroundColor; final double arcHeight; const ArcContainer({ super.key, required this.child, this.backgroundColor = Colors.white, this.arcHeight = 30, }); @override Widget build(BuildContext context) { return ClipPath( clipper: ArcCustomPainter(fillColor: backgroundColor, arcHeight: arcHeight), child: Container( color: backgroundColor, child: child, ), ); } }
参数调整技巧
- 弧形深浅:修改
arcHeight数值,正数越大凹陷越深,负数绝对值越大凸起越高 - 弧形宽度:调整
size.width * 0.25和size.width * 0.75的比例,控制弧形左右两端的起始位置 - 复杂弧形:若设计图为不对称或特殊弧度,将
quadraticBezierTo替换为cubicTo,通过两个控制点精准调整曲线形态
内容的提问来源于stack exchange,提问作者Azeez
相关产品推荐
相关产品推荐

