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

如何在CustomPainter中移除指定阴影线条?

解决方法

你的问题源于绘制阴影的路径超出了CustomPaint的尺寸范围,叠加模糊效果后,超出部分的阴影被显示了出来。可以通过以下两种方式解决:

方法一:裁剪画布范围

在绘制阴影前,将画布裁剪到CustomPaint的尺寸内,超出部分的阴影会被直接裁掉:

class RectanglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint fillPaint = Paint()
      ..color = Colors.deepPurpleAccent
      ..style = PaintingStyle.fill
      ..strokeWidth = size.width * 0.00
      ..strokeCap = StrokeCap.butt
      ..strokeJoin = StrokeJoin.miter;

    Path path_0 = Path();
    path_0.moveTo(size.width * 0.1490000, size.height * -0.0020000);
    path_0.lineTo(size.width * 0.1510000, size.height);
    path_0.lineTo(size.width * 0.6510000, size.height * 0.5020000);
    path_0.lineTo(size.width * 0.1490000, size.height * -0.0020000);
    path_0.close();

    Paint shadowPaint = Paint()
      ..color = Colors.black.withOpacity(0.3)
      ..blendMode = BlendMode.srcATop
      ..imageFilter = ImageFilter.blur(sigmaX: 0, sigmaY: 10);
    
    // 裁剪画布,限制阴影绘制范围
    canvas.save();
    canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height));
    canvas.drawPath(path_0, shadowPaint);
    canvas.restore();

    canvas.drawPath(path_0, fillPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

方法二:调整路径起点,避免超出范围

把路径中超出size.height的起点坐标改为0,让路径完全落在CustomPaint的尺寸范围内:

class RectanglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint fillPaint = Paint()
      ..color = Colors.deepPurpleAccent
      ..style = PaintingStyle.fill
      ..strokeWidth = size.width * 0.00
      ..strokeCap = StrokeCap.butt
      ..strokeJoin = StrokeJoin.miter;

    // 修改起点y坐标为0,消除超出范围的部分
    Path path_0 = Path();
    path_0.moveTo(size.width * 0.1490000, 0);
    path_0.lineTo(size.width * 0.1510000, size.height);
    path_0.lineTo(size.width * 0.6510000, size.height * 0.5020000);
    path_0.lineTo(size.width * 0.1490000, 0);
    path_0.close();

    Paint shadowPaint = Paint()
      ..color = Colors.black.withOpacity(0.3)
      ..blendMode = BlendMode.srcATop
      ..imageFilter = ImageFilter.blur(sigmaX: 0, sigmaY: 10);
    
    canvas.drawPath(path_0, shadowPaint);
    canvas.drawPath(path_0, fillPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

如果需要完全保留原图形的视觉效果,优先选择第一种裁剪画布的方式;第二种方法会让图形顶部有细微变化,但实现更直接。

内容的提问来源于stack exchange,提问作者Cyrus the Great

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 04:16:22