Flutter开发:如何填充自定义绘制中两个圆形之间的空白区域?
提问内容

我的圆形绘制类代码如下:
CircleWavePainter(this.animationValue) { //add some property to paint wavePaint = Paint() ..color = Colors.black.withAlpha(100) ..style = PaintingStyle.stroke ..strokeWidth = 1 ..isAntiAlias = true; }
我已经实现了两个圆形的绘制逻辑,现在需要填充两个圆之间的空白区域,相关绘制方法代码如下:
void paint(Canvas canvas, Size size) { //circle 1 canvas.drawCircle(Offset(size.height / 2, size.width / 2), 80 * (1.4 - animationValue / 2), wavePaint); //circle 2 canvas.drawCircle(Offset(size.height / 2, size.width / 2), 80 * (1.8 - animationValue / 2), wavePaint); }
解决方案
要实现两个同心圆之间的环形填充,你可以通过构造带奇偶填充规则的Path实现,具体修改步骤如下:
- 在
CircleWavePainter构造函数中新增填充专用的Paint实例:
CircleWavePainter(this.animationValue) { // 原有描边Paint配置 wavePaint = Paint() ..color = Colors.black.withAlpha(100) ..style = PaintingStyle.stroke ..strokeWidth = 1 ..isAntiAlias = true; // 新增环形填充Paint配置,可按需修改颜色透明度 fillPaint = Paint() ..color = Colors.black.withAlpha(100) ..style = PaintingStyle.fill ..isAntiAlias = true; }
- 修改
paint方法,构造环形路径后填充:
void paint(Canvas canvas, Size size) { final center = Offset(size.height / 2, size.width / 2); final innerRadius = 80 * (1.4 - animationValue / 2); final outerRadius = 80 * (1.8 - animationValue / 2); // 构造环形路径:使用奇偶填充规则自动挖去内圆区域 Path ringPath = Path() ..fillType = PathFillType.evenOdd ..addOval(Rect.fromCircle(center: center, radius: outerRadius)) ..addOval(Rect.fromCircle(center: center, radius: innerRadius)); // 填充环形区域 canvas.drawPath(ringPath, fillPaint); // 原有描边逻辑按需保留即可 canvas.drawCircle(center, innerRadius, wavePaint); canvas.drawCircle(center, outerRadius, wavePaint); }
该方案的核心是利用PathFillType.evenOdd的填充规则:路径范围内的点,穿过路径边界的次数为奇数时会被填充,偶数时不填充,添加外圆和内圆两条路径后,中间的环形区域刚好符合填充条件,完美实现需求。
内容的提问来源于stack exchange,提问作者Hoàng Phạm Đức
相关产品推荐
相关产品推荐

