如何创建自定义clipPath组件实现目标自定义Appbar效果?
你要的底部带圆弧凸起效果的自定义AppBar,可以通过自定义CustomClipper配合ClipPath组件实现,具体实现步骤和代码如下:
目标效果

实现步骤
- 第一步:自定义剪裁类,继承
CustomClipper<Path>,编写路径绘制逻辑
class CustomAppBarClipper extends CustomClipper<Path> { @override Path getClip(Size size) { final path = Path(); // 定位AppBar顶部两个顶点 path.lineTo(0, 0); path.lineTo(size.width, 0); // 定位AppBar右侧底部非凸起位置 path.lineTo(size.width, size.height - 40); // 绘制右侧圆弧到中间凸起最高点 final rightControlPoint = Offset(size.width * 0.75, size.height - 40); final centerPoint = Offset(size.width * 0.5, size.height); path.quadraticBezierTo(rightControlPoint.dx, rightControlPoint.dy, centerPoint.dx, centerPoint.dy); // 绘制左侧圆弧到AppBar左侧底部非凸起位置 final leftControlPoint = Offset(size.width * 0.25, size.height - 40); final leftBottomPoint = Offset(0, size.height - 40); path.quadraticBezierTo(leftControlPoint.dx, leftControlPoint.dy, leftBottomPoint.dx, leftBottomPoint.dy); path.close(); return path; } @override bool shouldReclip(covariant CustomClipper<Path> oldClipper) { return false; } }
- 第二步:使用
ClipPath组件包裹AppBar容器,绑定自定义的Clipper
ClipPath( clipper: CustomAppBarClipper(), child: Container( height: 200, // 自定义AppBar整体高度 color: Colors.blue, // 自定义AppBar背景色 padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: const [ Icon(Icons.menu, color: Colors.white, size: 24), Text("首页", style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold)), Icon(Icons.search, color: Colors.white, size: 24), ], ), ), )
如果要直接在Scaffold的appBar属性中使用,需要配合PreferredSize组件:
Scaffold( appBar: PreferredSize( preferredSize: const Size.fromHeight(200), child: ClipPath( clipper: CustomAppBarClipper(), child: Container( // 上述Container的配置内容 ), ), ), )
参数调整说明
- 调整代码里的
40数值,可修改底部凸起的高度,数值越大凸起幅度越高 - 调整贝塞尔曲线的控制点坐标
size.width * 0.75、size.width * 0.25,可修改圆弧的弯曲弧度 - 如果需要调整AppBar整体高度,修改Container的height属性和PreferredSize的preferredSize对应高度即可
内容的提问来源于stack exchange,提问作者Minh Tuan Văn
相关产品推荐
相关产品推荐

