Flutter中使用dart:ui Canvas绘制仅含圆角的检测框边框
实现带圆角的目标检测框边角(仅显示边角)
核心方案
通过Path分别绘制四个带圆角的L型边角,每个边角由两段直线+一段圆弧组成,既保留圆角效果,又只显示边角部分而非完整矩形边框。
完整代码实现
// 可动态调整的参数:边角延伸长度、圆角半径 final double cornerLength = 40.0; final double cornerRadius = 10.0; final Paint drawRectPaint = Paint() ..color = Colors.red ..style = PaintingStyle.stroke ..strokeWidth = 2.0; // 目标检测框的原始矩形区域 final rect = ui.Rect.fromLTWH(e.x, e.y, e.width, e.height); // 1. 绘制左上角圆角边角 Path topLeftPath = Path(); topLeftPath.moveTo(rect.left, rect.top + cornerLength); topLeftPath.lineTo(rect.left, rect.top + cornerRadius); // 绘制圆角圆弧(逆时针方向,贴合左上角) topLeftPath.arcToPoint( Offset(rect.left + cornerRadius, rect.top), radius: Radius.circular(cornerRadius), clockwise: false, ); topLeftPath.lineTo(rect.left + cornerLength, rect.top); canvas.drawPath(topLeftPath, drawRectPaint); // 2. 绘制右上角圆角边角 Path topRightPath = Path(); topRightPath.moveTo(rect.right - cornerLength, rect.top); topRightPath.lineTo(rect.right - cornerRadius, rect.top); topRightPath.arcToPoint( Offset(rect.right, rect.top + cornerRadius), radius: Radius.circular(cornerRadius), clockwise: false, ); topRightPath.lineTo(rect.right, rect.top + cornerLength); canvas.drawPath(topRightPath, drawRectPaint); // 3. 绘制右下角圆角边角 Path bottomRightPath = Path(); bottomRightPath.moveTo(rect.right, rect.bottom - cornerLength); bottomRightPath.lineTo(rect.right, rect.bottom - cornerRadius); bottomRightPath.arcToPoint( Offset(rect.right - cornerRadius, rect.bottom), radius: Radius.circular(cornerRadius), clockwise: false, ); bottomRightPath.lineTo(rect.right - cornerLength, rect.bottom); canvas.drawPath(bottomRightPath, drawRectPaint); // 4. 绘制左下角圆角边角 Path bottomLeftPath = Path(); bottomLeftPath.moveTo(rect.left + cornerLength, rect.bottom); bottomLeftPath.lineTo(rect.left + cornerRadius, rect.bottom); bottomLeftPath.arcToPoint( Offset(rect.left, rect.bottom - cornerRadius), radius: Radius.circular(cornerRadius), clockwise: false, ); bottomLeftPath.lineTo(rect.left, rect.bottom - cornerLength); canvas.drawPath(bottomLeftPath, drawRectPaint);
关键细节说明
- 参数可动态调整:
cornerLength和cornerRadius可以根据业务需求修改,比如根据检测框的大小自动适配:// 限制边角最长为40,同时不超过框宽/高的10% final double cornerLength = min(40.0, min(rect.width, rect.height) * 0.1); - 圆弧方向控制:
arcToPoint的clockwise: false确保圆弧向矩形内部弯曲,贴合检测框的角;如果设为true,圆弧会向外凸。 - Path绘制逻辑:每个边角都是从直线的一端开始,先画直线到圆弧起点,再画圆弧,最后画另一端的直线,形成带圆角的L型边角。
内容的提问来源于stack exchange,提问作者greenzebra
相关产品推荐
相关产品推荐

