Flutter中实现消息类Container自定义边框的问题咨询
Flutter四角自定义边框实现方案

这个效果可以通过Flutter自带的CustomPaint自定义绘制实现,无需引入第三方依赖,完整实现代码如下:
import 'package:flutter/material.dart'; class CornerBorderPainter extends CustomPainter { final Color borderColor; final double borderWidth; final double cornerLength; final double borderRadius; CornerBorderPainter({ required this.borderColor, this.borderWidth = 2, this.cornerLength = 20, this.borderRadius = 8, }); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = borderColor ..style = PaintingStyle.stroke ..strokeWidth = borderWidth; final path = Path(); // 左上角 path.moveTo(borderRadius, 0); path.lineTo(cornerLength, 0); path.moveTo(0, borderRadius); path.lineTo(0, cornerLength); // 右上角 path.moveTo(size.width - cornerLength, 0); path.lineTo(size.width - borderRadius, 0); path.moveTo(size.width, cornerLength); path.lineTo(size.width, borderRadius); // 右下角 path.moveTo(size.width - borderRadius, size.height); path.lineTo(size.width - cornerLength, size.height); path.moveTo(size.width, size.height - cornerLength); path.lineTo(size.width, size.height - borderRadius); // 左下角 path.moveTo(cornerLength, size.height); path.lineTo(borderRadius, size.height); path.moveTo(0, size.height - cornerLength); path.lineTo(0, size.height - borderRadius); canvas.drawPath(path, paint); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) => false; } // 使用示例 class CornerBorderDemo extends StatelessWidget { const CornerBorderDemo({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: CustomPaint( painter: CornerBorderPainter( borderColor: Colors.blueAccent, borderWidth: 3, cornerLength: 25, borderRadius: 12, ), child: const SizedBox( width: 300, height: 200, child: Center( child: Text("自定义边框内容区域", style: TextStyle(fontSize: 16)), ), ), ), ), ); } }
参数说明
borderColor:自定义边框颜色borderWidth:边框线条粗细cornerLength:四个角落边框的长度borderRadius:边角位置的圆角适配值
如果需要在边框内部放内容,直接把内容组件作为CustomPaint的child传入即可,内容区域的大小会自动匹配CustomPaint的尺寸。如果需要实现边框动画效果,修改shouldRepaint返回值为true,结合动画控制器动态修改参数即可。
内容的提问来源于stack exchange,提问作者Fazaa Majdeddine
相关产品推荐
相关产品推荐

