【问题标题】:Flutter CustomPaint shadowFlutter CustomPaint 阴影
【发布时间】:2018-12-02 21:34:25
【问题描述】:

我有以下小部件:

class OutsiderButton extends StatelessWidget {

  final Function onPressed;
  final Icon icon;
  final OutsiderButtonPosition position;

  OutsiderButton({this.onPressed, @required this.icon, this.position});

  @override
  Widget build(BuildContext context) {
    return new Stack(fit: StackFit.loose, alignment: Alignment.center, children: [
      new CustomPaint(
        painter: new _OutsiderShape(position: position),
        size: Size(60.0, 60.0),
        isComplex: false,
      ),
      OutlineButton(
        borderSide: BorderSide(width: 1.0, color: Colors.white),
        color: AppThemeColors.accentColor,
        shape: new CircleBorder(),
        child: new Padding(
          padding: const EdgeInsets.all(6.0),
          child: icon,
        ),
        onPressed: onPressed,
      )
    ]);
  }
}

它使用CustomPainter 来绘制背景。我需要这个CustomPainter 来绘制阴影,但是每次单击小部件时,阴影都会重新绘制并且变得越来越强。这里是CustomPainter

class _OutsiderShape extends CustomPainter {

  final Paint bookMarkPaint;
  final double hexagonOffset = 15.0;
  final OutsiderButtonPosition position;
  Path path = Path();

  _OutsiderShape({this.position = OutsiderButtonPosition.TOP}) : bookMarkPaint = new Paint() {
    bookMarkPaint.color = AppThemeColors.primaryColorLight;
    bookMarkPaint.style = PaintingStyle.fill;
  }

  @override
  void paint(Canvas canvas, Size size) {

    canvas.save();

    if (position == OutsiderButtonPosition.BOTTOM) {
      canvas.rotate(pi);
      canvas.translate(-size.width, -size.height);
    }

    path.moveTo(0.0, hexagonOffset);
    path.relativeLineTo(size.width / 3, -hexagonOffset);
    path.relativeLineTo(size.width / 3, 0.0);
    path.relativeLineTo(size.width / 3, hexagonOffset);
    path.relativeLineTo(0.0, size.height - hexagonOffset);
    path.relativeLineTo(-size.width, 0.0);
    path.close();

    canvas.drawShadow(path, Colors.grey[900], 2.0, false);
    canvas.drawPath(path, bookMarkPaint);

    canvas.restore();
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

这是单击四次后阴影的样子。

如何避免这种行为?

【问题讨论】:

    标签: widget flutter shadow custom-painting


    【解决方案1】:

    这一行的问题

    //problem here 
    canvas.drawShadow(path, Colors.grey[900], 2.0, false)
    
    //change the alpha color of your grey color like this 
    canvas.drawShadow(path, Colors.grey.withAlpha(50), 4.0, false);
    

    【讨论】:

      【解决方案2】:

      我的猜测是 Flutter 在重绘之前不会清除画布,所以你是在现有的阴影上绘制。

      您可以尝试在 paint 方法的开头手动清除画布:

      canvas.drawColor(Color(0), BlendMode.clear);
      

      【讨论】:

      • 我尝试运行您的代码 sn-p,但无法重现该问题。你在运行最新版本的颤振吗?要找出问题所在,我建议您发布完整的代码 sn-p。
      猜你喜欢
      • 2022-10-19
      • 1970-01-01
      • 2020-02-23
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 2020-01-12
      相关资源
      最近更新 更多