flutter - Flutter:如何在CustomPainter对象中设置动态颜色

标签 flutter dart flutter-layout

为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])

预期结果:

enter image description here

当前结果:

enter image description here

最佳答案

正如@pskink在评论中提到的,我已经阅读了文档,并且我想到了我缺少十六进制代码中的Alpha值。

如下更改utils.dart文件,它对我来说很好。

class Utils{

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

    ];
  }
}

关于flutter - Flutter:如何在CustomPainter对象中设置动态颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58972965/

相关文章:

php - Dart 与 PHP 代码中的不同哈希结果

flutter - 将地理定位器 GPS 流与 Riverpod StreamProvider 结合使用

flutter - 如何以最好的方式实现图标下的动态文本

flutter - Flutter 容器中的图标间距

dart - Flutter Copy & Past Popup 从视口(viewport)溢出

flutter - 在flutter插件image_picker示例中从图库中选择图像时内存增加

flutter - Flutter 是否有在移动和 Web 应用程序之间共享代码的好方法?

dart - fontFamily 属性在 flutter 中无法正常工作

dart - super 和 Key 在 flutter 中做了什么?

go - Flutter,在预构建的 GO .so 库上使用 DynamicLibrary.open(),无需编写 Native Code(Java/Swift)