簡體   English   中英

"Flutter CustomPaint 陰影"

[英]Flutter CustomPaint shadow

我有以下小部件:

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;
  }
}

這是單擊四次后陰影的樣子。

錯誤的影子

我怎樣才能避免這種行為?

這一行的問題

//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);

我的猜測是 Flutter 在重繪之前不會清除畫布,因此您正在繪制現有陰影。

您可以嘗試在paint方法開始時手動清除畫布:

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

您的代碼中有canvas.save行。 這就是它被保存的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM