You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter 自定义绘制圆弧(Arc)如何实现符合要求的底部阴影效果

优化后完整代码

import 'dart:math' as Math;
import 'package:flutter/material.dart';

class ArcPainter extends CustomPainter {

  @override
  void paint(Canvas canvas, Size size) {
    final double radius = Math.min(size.width / 2, size.height);
    final center = Offset(size.width / 2.0, size.height / 2.0);
    const strokeWidth = 12.0;

    final rect = Rect.fromCircle(center: center, radius: radius);
    // 生成基础圆弧路径
    final Path arcPath = Path()
      ..arcTo(rect, Math.pi, Math.pi, false);
    final paint = Paint()
      ..color = const Color(0xFFC4C4C4)
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeWidth = strokeWidth;
    // 将描边样式转换为实际绘制的轮廓路径,自动包含圆角端点形状
    final Path strokePath = paint.createStroke(rect)
        .convert(arcPath);

    // 先绘制阴影再绘制主圆弧,避免阴影覆盖主圆弧
    canvas.drawShadow(
      strokePath.shift(const Offset(0, 2)), // 阴影仅向下轻微偏移,控制范围
      const Color(0x66000000), // 降低阴影不透明度更自然
      6, // 缩小模糊半径,实现窄范围阴影效果
      true,
    );
    canvas.drawArc(rect, Math.pi, Math.pi, false, paint);
  }

  // 修正原代码的参数类型错误
  @override
  bool shouldRepaint(ArcPainter oldDelegate) => false;
}

改动说明

  • 仅保留圆弧正下方窄范围阴影:不再使用原始空心圆弧路径生成阴影,通过Paint.createStroke()将描边转换为实际绘制的轮廓路径,阴影只会沿描边路径生成,不会填充整个半圆区域;配合缩小阴影模糊半径、仅设置向下小偏移,严格控制阴影范围。
  • 消除圆弧与阴影的白色间隙:调整绘制顺序,先绘制阴影再绘制主圆弧,让主圆弧完全覆盖阴影上半部分,自然消除间隙。
  • 阴影覆盖两端圆角笔触:createStroke()转换路径时会自动将StrokeCap.round的圆角端点轮廓纳入路径,生成的阴影自然会覆盖两端的圆角区域。

内容的提问来源于stack exchange,提问作者Adam Griffiths

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 22:48:02