【问题标题】:Flutter : How to set dynamic color in CustomPainter objectFlutter:如何在 CustomPainter 对象中设置动态颜色
【发布时间】:2019-11-21 10:41:56
【问题描述】:

为 CustomPainter 的构造函数动态设置油漆颜色不起作用。

lines_painter.dart

class LinesPainter extends CustomPainter {
  final double lineHeight = 8;
  final int maxLines = 60;
  final Color customColor;

  LinesPainter(this.customColor);

  @override
  void paint(Canvas canvas, Size size) {
    canvas.translate(size.width / 2, size.height / 2);

    canvas.save();
    final Paint linePainter = Paint()
      ..color = customColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.5;
    final radius = size.width / 2;

    List.generate(maxLines, (i) {
      var newRadius = (i % 5 == 0) ? radius - 15 : radius - 5;
      canvas.drawLine(Offset(0, radius), Offset(0, newRadius), linePainter);
      canvas.rotate(2 * pi / maxLines);
    });

    canvas.restore();
  }

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

utils.dart

class Utils{

  List<Color> getColorsArray (){
    return [
      Color(0xff5733),
      Color(0xc70039),
      Color(0x900c3e),
      Color(0x571845),
      Color(0x251e3e),
      Color(0x051e3e),

    ];
  }
}

下面的代码应该用线条绘制圆形

LinesPainter(Utils().getColorsArray()[0])

预期结果:

当前结果:

【问题讨论】:

  • paint()方法中添加print(customColor),你看到了什么?
  • print(customColor) //OutPut I/flutter (4320): Color(0x00ff5733)
  • 所以你需要Color(0xffff5733) - 和数组中的其他颜色一样
  • 我没听懂。你能详细说明一下吗?

标签: flutter dart flutter-layout


【解决方案1】:

正如@pskink 在 cmets 中提到的那样,我已经阅读了文档,并且我知道我在十六进制代码中缺少 Alpha 值。

像下面这样在 utils.dart 文件中进行更改,它对我来说很好。

class Utils{

  List<Color> getColorsArray (){
    return [
      Color(0xffff5733),
      Color(0xffc70039),
      Color(0xff900c3e),
      Color(0xff571845),
      Color(0xff251e3e),
      Color(0xff051e3e),

    ];
  }
}

【讨论】:

  • 嗯....这是我开始使用 Flutter 时遇到的第一件事 aaaahaaaa。 :))。另外仅供参考,Colorr 类有 2 个不错的方法。 withOpacitywithAlpha 你也应该检查一下
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 2017-07-10
  • 2019-10-17
  • 1970-01-01
相关资源
最近更新 更多