Flutter实现自定义曲线卡片形状时无法绘制正确圆角的问题求助
实现自定义曲线卡片的解决方案
你需要修改Chevron自定义绘制类中的Path路径逻辑,使用二次贝塞尔曲线quadraticBezierTo替换原来的直边绘制,就能得到带圆角弯曲的效果。
完整修改后的代码
Container( child: Center( child: CustomPaint( painter: Chevron(), child: Container( width: 120.0, height: 140.0, child: Padding( padding: EdgeInsets.only(top: 30.0), child: Align( alignment: Alignment.topCenter, child: Text("1", style: TextStyle(fontSize: 24.0)), ), ), ), ), ), ); class Chevron extends CustomPainter { @override void paint(Canvas canvas, Size size) { final Gradient gradient = LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.orangeAccent, Colors.yellow], tileMode: TileMode.clamp, ); final Rect colorBounds = Rect.fromLTRB(0, 0, size.width, size.height); final Paint paint = Paint()..shader = gradient.createShader(colorBounds); Path path = Path(); // 起点:左侧顶部 path.moveTo(0, 30); // 左侧垂直边到底部 path.lineTo(0, size.height); // 底部水平边到右下角 path.lineTo(size.width, size.height); // 右侧垂直边到右上角 path.lineTo(size.width, 0); // 核心修改:用二次贝塞尔曲线绘制带圆角的顶部弯曲边 // 第一个参数是控制点坐标,第二个参数是曲线终点坐标 path.quadraticBezierTo(size.width * 0.5, 15, 0, 30); path.close(); canvas.drawPath(path, paint); } @override bool shouldRepaint(CustomPainter oldDelegate) => false; }
参数调整说明
- 如需调整弯曲的弧度大小,可修改
quadraticBezierTo的控制点Y轴数值,数值越小凹陷越深,数值越大弧度越平缓 - 如需调整圆角的圆润程度,可换成三次贝塞尔曲线
cubicTo设置两个控制点实现更精细的效果
内容的提问来源于stack exchange,提问作者Joan Nabusoba
相关产品推荐
相关产品推荐

