Flutter颜色生成插件rainbow_color的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter颜色生成插件rainbow_color的使用

简介

rainbow_color 是一个用于简化数值域到多色范围插值的Flutter插件。它接受一个数值域(即开始和结束数字)和两个或更多颜色组成的光谱,并提供列表访问操作符 [] 以进行插值。

该包还提供了 RainbowColorTween,这是标准 ColorTween 的多色变体,消除了为等权重转换构建更复杂的 TweenSequence 的需求。

示例

使用方法

插值颜色

要在一个光谱中插值颜色,可以使用列表访问操作符:

import 'package:rainbow_color/rainbow_color.dart';

void main() {
  var rb = Rainbow(
    spectrum: [Color(0xFFFF0000), Color(0xFFFFFFFF), Color(0xff00ff00)],
    rangeStart: -10,
    rangeEnd: 10,
  );
  Color warmColor = rb[-9.32];
  Color coldColor = rb[8.44];
}

使用 RainbowColorTween

在动画中使用 RainbowColorTween 来替代 ColorTween,以便在多个颜色之间进行插值:

@override
void initState() {
  super.initState();
  _controller = AnimationController(duration: widget.duration, vsync: this);
  _clAnim = RainbowColorTween([Color(0x33FFAAAA), Color(0x33000000), Color(0x00000000)])
      .animate(_controller)
      ..addListener(() {
        setState(() {});
      });
}

示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中使用 rainbow_color 插件:

import 'package:flutter/material.dart';
import 'package:rainbow_color/rainbow_color.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Rainbow Color Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController controller;

  final Rainbow _rb = Rainbow(
    spectrum: const [
      Colors.red,
      Colors.orange,
      Colors.yellow,
      Colors.green,
      Colors.blue,
      Colors.indigo,
      Colors.purple,
      Colors.red,
    ],
    rangeStart: 0.0,
    rangeEnd: 300.0,
  );

  @override
  void initState() {
    super.initState();
    controller = AnimationController(duration: const Duration(seconds: 5), vsync: this);

    animation = Tween<double>(begin: _rb.rangeStart.toDouble(), end: _rb.rangeEnd.toDouble())
        .animate(controller)
          ..addStatusListener((status) {
            if (status == AnimationStatus.completed) {
              controller.reset();
              controller.forward();
            } else if (status == AnimationStatus.dismissed) {
              controller.forward();
            }
          });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ColorCycler(),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

class ColorCycler extends StatefulWidget {
  @override
  _ColorCyclerState createState() => _ColorCyclerState();
}

class _ColorCyclerState extends State<ColorCycler> with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController controller;

  final Rainbow _rb = Rainbow(
    spectrum: const [
      Colors.red,
      Colors.orange,
      Colors.yellow,
      Colors.green,
      Colors.blue,
      Colors.indigo,
      Colors.purple,
      Colors.red,
    ],
    rangeStart: 0.0,
    rangeEnd: 300.0,
  );

  @override
  void initState() {
    super.initState();
    controller = AnimationController(duration: const Duration(seconds: 5), vsync: this);

    animation = Tween<double>(begin: _rb.rangeStart.toDouble(), end: _rb.rangeEnd.toDouble())
        .animate(controller)
          ..addStatusListener((status) {
            if (status == AnimationStatus.completed) {
              controller.reset();
              controller.forward();
            } else if (status == AnimationStatus.dismissed) {
              controller.forward();
            }
          });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: AnimatedBuilder(
        animation: animation,
        builder: (BuildContext context, _) => Column(
          children: <Widget>[
            ColorText(),
            Container(
              height: 250.0,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      _rb[animation.value],
                      _rb[(50.0 + animation.value) % _rb.rangeEnd]
                    ]),
                border: Border.all(
                  color: Colors.black,
                  width: 4,
                ),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Padding(
                padding: const EdgeInsets.all(24.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    GreyScaleCycler(
                        baseColor: _rb[animation.value],
                        duration: const Duration(seconds: 5),
                        text: "Foo"),
                    GreyScaleCycler(
                        baseColor: _rb[(50.0 + animation.value) % _rb.rangeEnd],
                        duration: const Duration(seconds: 8),
                        text: "Bar",
                        leftToRight: false),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0),
              child: Container(
                height: 50.0,
                child: new Column(
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: List.generate(10, (index) => index / 10)
                          .map((s) => Container(
                              height: 45.0,
                              width: 30.0,
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                    colors: [
                                      Rainbow(spectrum: [
                                        _rb[animation.value],
                                        _rb[(50.0 + animation.value) % _rb.rangeEnd]
                                      ])[s],
                                      Color(0xffffff)
                                    ]),
                              )))
                          .toList(),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

class ColorText extends StatefulWidget {
  @override
  _ColorTextState createState() => _ColorTextState();
}

class _ColorTextState extends State<ColorText> with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<Color> _colorAnim;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(duration: Duration(seconds: 3), vsync: this);
    _colorAnim = RainbowColorTween([Colors.blue, Colors.green, Colors.red, Colors.blue])
        .animate(controller)
          ..addListener(() {
            setState(() {});
          })
          ..addStatusListener((status) {
            if (status == AnimationStatus.completed) {
              controller.reset();
              controller.forward();
            } else if (status == AnimationStatus.dismissed) {
              controller.forward();
            }
          });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Text("Hello!", style: TextStyle(color: _colorAnim.value));
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

class GreyScaleCycler extends StatefulWidget {
  const GreyScaleCycler({
    Key? key,
    required this.baseColor,
    required this.text,
    required this.duration,
    this.leftToRight = true,
  }) : super(key: key);

  final Color baseColor;
  final Duration duration;
  final bool leftToRight;
  final String text;

  static const List<Color> spectrum = [
    Colors.white,
    const Color(0x33ffffff),
    const Color(0x33000000),
    Colors.black,
    const Color(0x33000000),
    const Color(0x33ffffff),
    Colors.white
  ];

  @override
  _GreyScaleCyclerState createState() => _GreyScaleCyclerState();
}

class _GreyScaleCyclerState extends State<GreyScaleCycler> with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<Color> _bwAnim;
  late Animation<Color> _wbAnim;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(duration: widget.duration, vsync: this);
    _wbAnim = RainbowColorTween(GreyScaleCycler.spectrum).animate(controller);
    _bwAnim = RainbowColorTween(GreyScaleCycler.spectrum).animate(controller)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          controller.reset();
          controller.forward();
        } else if (status == AnimationStatus.dismissed) {
          controller.forward();
        }
      });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 55.0,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [widget.baseColor, _bwAnim.value],
          begin: widget.leftToRight ? Alignment.centerLeft : Alignment.centerRight,
          end: widget.leftToRight ? Alignment.centerRight : Alignment.centerLeft,
        ),
        border: Border.all(
          color: Colors.black87,
          width: 4,
        ),
        borderRadius: BorderRadius.circular(12),
      ),
      child: SizedBox(
        width: double.infinity,
        child: Center(
          child: Text(widget.text,
              textAlign: TextAlign.center,
              style: TextStyle(color: _wbAnim.value, fontSize: 24.0)),
        ),
      ),
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

这个示例代码展示了如何在Flutter应用中使用 rainbow_color 插件来创建一个彩色渐变动画效果。你可以根据需要调整颜色光谱、动画持续时间和其他参数。


更多关于Flutter颜色生成插件rainbow_color的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter颜色生成插件rainbow_color的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用Flutter颜色生成插件rainbow_color的代码案例。这个插件可以帮助你生成彩虹色渐变或其他基于彩虹色系的颜色。

首先,你需要在你的pubspec.yaml文件中添加rainbow_color依赖:

dependencies:
  flutter:
    sdk: flutter
  rainbow_color: ^latest_version  # 请替换为实际的最新版本号

然后,运行flutter pub get来获取依赖。

接下来,你可以在你的Flutter应用中使用这个插件来生成彩虹颜色。以下是一个简单的示例,展示了如何使用rainbow_color插件来生成颜色,并在一个容器中使用这些颜色:

import 'package:flutter/material.dart';
import 'package:rainbow_color/rainbow_color.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Rainbow Color Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: RainbowColorDemo(),
    );
  }
}

class RainbowColorDemo extends StatefulWidget {
  @override
  _RainbowColorDemoState createState() => _RainbowColorDemoState();
}

class _RainbowColorDemoState extends State<RainbowColorDemo> {
  final int numberOfColors = 10; // 你想要生成的彩虹颜色数量
  List<Color> rainbowColors = [];

  @override
  void initState() {
    super.initState();
    // 生成彩虹颜色
    rainbowColors = generateRainbowColors(numberOfColors);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Rainbow Color Demo'),
      ),
      body: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
        ),
        itemCount: rainbowColors.length,
        itemBuilder: (context, index) {
          return Container(
            color: rainbowColors[index],
            child: Center(
              child: Text(
                'Color ${index + 1}',
                style: TextStyle(color: Colors.white),
              ),
            ),
          );
        },
      ),
    );
  }

  // 使用rainbow_color插件生成彩虹颜色
  List<Color> generateRainbowColors(int count) {
    List<Color> colors = [];
    for (int i = 0; i < count; i++) {
      double ratio = i / (count - 1.0); // 计算当前颜色在彩虹中的比例
      Color color = RainbowColor.fromRatio(ratio);
      colors.add(color);
    }
    return colors;
  }
}

在这个示例中,我们首先导入了rainbow_color包,然后在_RainbowColorDemoState类中,我们在initState方法中生成了一系列彩虹颜色。generateRainbowColors方法接受一个整数参数count,表示你想要生成的颜色数量,并返回一个颜色列表。我们使用RainbowColor.fromRatio方法来根据比例生成彩虹颜色。

build方法中,我们使用GridView.builder来显示这些颜色。每个颜色都被显示在一个容器中,容器中心有一个显示颜色索引的文本。

请注意,实际使用中,RainbowColor.fromRatio方法可能需要根据rainbow_color插件的实际API进行调整。如果插件提供了不同的方法来生成颜色,你可能需要相应地修改代码。

希望这个示例对你有所帮助!

回到顶部