如何在Flutter中绘制用作边框的3/4圆(四分之一区域透明)

Flutter 3/4圆形边框实现方案
以下提供两种常用的实现方式,可根据场景选择:
方案1:自定义CustomPaint绘制(推荐)
无需依赖背景色适配,适配所有场景(渐变背景、图片背景都可用),核心思路是直接通过Canvas绘制270度的圆弧边框,剩余90度区域默认透明。
完整代码实现
import 'package:flutter/material.dart'; class ThreeQuarterCircleBorder extends StatelessWidget { // 边框宽度 final double strokeWidth; // 边框颜色 final Color color; // 圆形整体尺寸 final double size; const ThreeQuarterCircleBorder({ super.key, required this.strokeWidth, required this.color, required this.size, }); @override Widget build(BuildContext context) { return CustomPaint( size: Size(size, size), painter: _ThreeQuarterPainter( strokeWidth: strokeWidth, color: color, ), ); } } class _ThreeQuarterPainter extends CustomPainter { final double strokeWidth; final Color color; _ThreeQuarterPainter({ required this.strokeWidth, required this.color, }); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = strokeWidth ..color = color ..strokeCap = StrokeCap.round; // 可选配置,让边框两端更圆润 // 绘制圆弧:从顶部-90度开始,顺时针扫过270度(即3/4个圆) canvas.drawArc( Rect.fromLTWH( strokeWidth / 2, strokeWidth / 2, size.width - strokeWidth, size.height - strokeWidth, ), -3.1415926 / 2, // 起始角度(弧度值,对应-90度) 3 * 3.1415926 / 2, // 扫过角度(弧度值,对应270度) false, paint, ); } @override bool shouldRepaint(covariant _ThreeQuarterPainter oldDelegate) { return oldDelegate.color != color || oldDelegate.strokeWidth != strokeWidth; } }
调用示例
ThreeQuarterCircleBorder( strokeWidth: 4, color: Colors.blueAccent, size: 80, )
方案2:Stack组合裁切实现(适合纯色背景场景)
实现逻辑更简单,先绘制完整的圆形边框,再用和页面背景同色的组件遮挡住1/4的区域即可,仅适配纯色背景场景。
完整代码实现
class StackThreeQuarterCircle extends StatelessWidget { final double strokeWidth; final Color borderColor; final double size; // 需要传入和页面背景一致的颜色,用于遮挡1/4区域 final Color backgroundColor; const StackThreeQuarterCircle({ super.key, required this.strokeWidth, required this.borderColor, required this.size, required this.backgroundColor, }); @override Widget build(BuildContext context) { return SizedBox( width: size, height: size, child: Stack( children: [ // 完整的圆形边框 Container( decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(color: borderColor, width: strokeWidth), ), ), // 遮挡右下角1/4区域 Positioned( right: 0, bottom: 0, child: Container( width: size / 2, height: size / 2, color: backgroundColor, ), ) ], ), ); } }
内容的提问来源于stack exchange,提问作者mohsen tavosi
相关产品推荐
相关产品推荐

