Flutter颜色分析插件spectrum的使用
Flutter颜色分析插件spectrum的使用
spectrum
pub.dev Listing | API Doc | GitHub
Gradient API References:
GradientUtils | GradientTween | Steps | FooShadedSteps | AnimatedGradient
Color API References:
Shading | ColorOperators | ColorOperatorsMethods | Spectrum | SpectrumUtils
More:
ColorArithmetic | StopsArithmetic | SwatchMode | GradientStoryboard | NillGradients | MaterialColorToList
🐸 Zaba.app ― simple packages, simple names.

一个彩虹般的颜色和渐变工具包,例如 GradientTween,渐变的 copyWith(),各种潜在参数,Steps-type 渐变,颜色的 complementary(),AnimatedGradient,MaterialColor 生成,以及其他功能!
📚 Table of Contents

- 🌊 Gradients
- 💫 Interpolation
 - 🌈 Steps
- 🧹 Softness
 - 🕶️ Shaded Steps
 
 - ⏰ Animation
- 📖 Gradient Storyboard
 
 - 📋 Override Copy With
 
 - 🎨 Colors
- ➗ Operators
 - 🗜️ Spectrum
 - 🤝 Complementary Colors
 
 - 🛣️ Roadmap
 
🌊 Gradients
可以将任何已实例化的 Gradient 使用漂亮的 Gradient.copyWith() 方法来覆盖一些或所有属性。此方法接受所有类型的潜在 Gradient 子类型属性,并仅应用必要的属性。
这个 GradientUtils 扩展方法在整个
spectrum的其他部分中用作默认的 “copy with” 函数。这是通过私有方法spectrumCopyWith()实现的,该方法满足默认上下文中未初始化构造函数参数overrideCopyWith的 GradientCopyWith 类型别名定义。
另一个渐变实用程序是简单的 getter Gradient.reversed,它返回具有相同属性但其 colors(以及解释或显式的 stops)顺序相反的渐变。
💫 Interpolation
平滑的 Gradient 插值不仅仅通过 Gradient.lerp()…哦不,这还不够。
此包提供了完整的定制 IntermediateGradient,用于在不同类型的渐变之间进行真正平滑且令人眼花缭乱的渐变动画!

插值后的 Gradient 可通过 GradientTween.evaluate(Animation animation) 或 transform(double t) 获得。
提示:
在更好的List插值实现之前,可以尝试使用isAgressive。
🌈 Steps
Spectrum 还添加了全新的渐变类型称为 Steps,以及名为 FooShadedSteps 的阴影变体。想象一种渐变,它打破了平滑过渡的想法,而不是在颜色之间平滑过渡,而是创建一系列硬步骤。

这是通过本质上复制 <Color> 的列表 colors 和(解释或显式的)<double> 的列表 stops 来实现的。作为这个过程的产品,任何显式初始化的 stops 列表都不应该以 1.0 结尾,否则该停止会被吃掉。例如,一个三色的 Steps 可能有 stops: [0.0, 0.3, 0.8]。
🧹 Softness
可以根据偏好或用户设备的显示密度增加或零化 softness。高分辨率屏幕看起来很好,硬边的颜色之间没有别扭感。低分辨率屏幕会从 softness 中受益,以提供一个附加的元素,当复制停止时,每个第二项都有一个小增量。
想象一下
Steps.stops是[0.0, 0.3, 0.8]。提供一个softness值为0.001,则此渐变的有效解析停止现在是:[0.0, 0.001, 0.3, 0.3001, 0.8, 0.8001]。

较大的 softness 会使 Steps 更像其原始 Gradient 对应物。相邻的例子是从 softness: 0.0 过渡到 softness: 0.14。
🕶️ Shaded Steps
现在想象一下更复杂的内在颜色和停止数学,产生各种自动生成的渐变……比如 FooShadedSteps 可能诞生。

每个 Linear、Radial 和 Sweep 都扩展自原始的 Steps 对应物,并覆盖其 steppedColors 和 steppedStops 属性,实际上将其列表“四倍化”,可选地带有多种可定制参数(包括执行颜色阴影的函数)。
⏰ Animation
提供一个动画,如 AnimationController 给 AnimatedGradient,并指定要改变属性的渐变。
通过调用 AnimatedGradient.observe 或使用 GradientUtils.animate 的便捷方法获得实际的 Gradient 输出。
当然,您可以为属性提供多个 Tween,如 Gradient.center 或 Gradient.begin,并且这些属性可以通过 TweenSpec 提供;但是考虑其他特殊功能:GradientAnimation.colorArithmetic 和 GradientAnimation.stopsArithmetic。
提问:
TweenSpec是一种新的typedef形式,其定义是Map而不是Function。
📖 Gradient Storyboard
所有的动画描述都适合于 GradientStoryboard。storyboard 将一个或多个 GradientAnimation 枚举常量映射到相关的描述对象。
提示:
(未来可能会发生功能变化。)
上述软度和阴影步骤示例图都是由 AnimatedGradient 制作的。
GradientAnimation (storyboard key) | 
Description Object (storyboard value) | 
Literal | 
|---|---|---|
colorArithmetic | 
ColorArithmetic | 
Color Function(Color color, double factor) | 
stopsArithmetic | 
StopsArithmetic | 
double Function(double stop, double factor) | 
tweenSpec | 
"TweenSpec" | 
Map<GradientProperty, Tween<dynamic>> | 
none | 
null / anything | 
null / anything | 
final animatedGradient = AnimatedGradient(
  controller: _controller,
  gradient: RadialSteps(colors: Colors.red.complementTriad),
  storyboard: {
    GradientAnimation.colorArithmetic: Shades.withOpacity,
    GradientAnimation.stopsArithmetic: Maths.subtraction,
    GradientAnimation.tweenSpec: {
      GradientProperty.center: Tween<AlignmentGeometry>(
          begin: const Alignment(1, 1), end: const Alignment(-1, -1)),
      GradientProperty.focal: Tween<AlignmentGeometry>(
          begin: const Alignment(3, -1), end: const Alignment(-3, -1)),
      GradientProperty.radius: Tween<double>(begin: 0.5, end: 0),
      GradientProperty.focalRadius: Tween<double>(begin: 2, end: 0),
      GradientProperty.startAngle: Tween<double>(
          begin: -1.0 * 3.1415927, end: 0.0 * 3.1415927),
      GradientProperty.endAngle: Tween<double>(
          begin: 2.0 * 3.1415927, end: 4.0 * 3.1415927),
      GradientProperty.shadeFactor: StepTween(begin: -200, end: 0),
      GradientProperty.softness: Tween<double>(begin: 0, end: 0.14),
    },
  },
);
提示:
不适用于所提供Gradient类型的任何属性都会被忽略。
📋 Override Copy With
作为一个高级功能,如果您正在操作自定义的 Gradient 类型,而该类型不会被此包硬编码识别,则可以覆盖 GradientCopyWith 函数。
此覆盖函数预期接受大量潜在参数,并可以编程返回您的自定义类型。
例如,在 GradientTween 或 AnimatedGradient 中提供此 GradientCopyWith 函数:
Gradient customCopyWith(Gradient original, { List<Color>? colors, List<double>? stops, ... /* remaining potential parameters */ })
    => CustomGradient(
         colors: colors ?? original.colors,
         stops: stops ?? original.stops,
         ... );
---
final tween = GradientTween(
  begin: customGradient,
  end: differentCustomGradient,
  overrideCopyWith: customCopyWith);
🎨 Colors
➗ Operators
ColorOperators 也已准备就绪,还有一些不错的方法。
除了用于颜色反转、平均两个颜色、添加或减去颜色等操作符外,还有用于随机选择颜色的运算符。
extension ColorOperators on Color { ... }
extension ColorOperatorsMethods on Color { ... }
// TODO: 示例操作符用法。
🗜️ Spectrum
一个名为 Spectrum 的抽象类提供了一些帮助函数,例如 Spectrum.alphaChannel(),它执行与参数 strength 描述相同的函数。
另一个静态函数 Spectrum.materialColor() 允许从单个 Color 值生成完整的 [MaterialColor] 色板,具有可定制选项。可用模式包括:SwatchMode.shade 或 SwatchMode.desaturate,以及更专业的模式 SwatchMode.complements 和 SwatchMode.fade。

final color0 = Spectrum.materialColor(
    color,
    mode: SwatchMode.shade,
    factor: 200,
);
// 提示:上面有快捷方式:`color.asMaterialColor`,使用 shade @ 200
final color0a = Spectrum.materialAccent(
    color,
    mode: SwatchMode.shade,
    factor: 200,
);
// 提示:上面有快捷方式:`color.asMaterialAccent`,使用 shade @ 200
final color1 = Spectrum.materialColor(
    color,
    mode: SwatchMode.desaturate,
    // factor: 0.2, // 覆盖透明度/alpha
);
final color2 = Spectrum.materialColor(
    color,
    mode: SwatchMode.fade,
    // factor: 100 // TODO: 提供与 SwatchMode.shade 相同的着色范围,
    // (目前仅执行 .withWhite(factor) 在提供的颜色上)
);
final color3a = Spectrum.materialAccent(
    color,
    mode: SwatchMode.complements,
);
提示:
使用 MaterialColor 和 MaterialAccentColor 上的扩展,使用 getterasList或方法toList()将这些色板转换为简化的<List<Color>>,例如:
// getter 不会在列表开头插入“primary”颜色。(通常映射为 `shade500`)
final List<Color> shadesColor0 = color0.asList;
// 方法有一个标志来在列表开头插入“primary”。默认值为 `true` 以区分 `asList` 的灵活性。
final List<Color> shadesColor3a = color3a.toList(includePrimary: false);
这使得 MaterialColor 或 accent 颜色成为馈送 Gradient.colors 的绝佳候选。
final matColorGradient = LinearGradient(colors: shadesColor0);
更多关于Flutter颜色分析插件spectrum的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter颜色分析插件spectrum的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中,spectrum 是一个用于颜色分析的插件,它可以帮助你从图像中提取颜色信息。使用 spectrum 插件,你可以从图像中获取主色调、调色板等信息,这对于设计、图像处理等应用场景非常有用。
安装 spectrum 插件
首先,你需要在 pubspec.yaml 文件中添加 spectrum 插件的依赖:
dependencies:
  flutter:
    sdk: flutter
  spectrum: ^1.0.0  # 请检查最新版本
然后运行 flutter pub get 来安装插件。
使用 spectrum 插件
1. 导入插件
import 'package:spectrum/spectrum.dart';
2. 从图像中提取颜色信息
你可以使用 Spectrum 类来从图像中提取颜色信息。以下是一个简单的示例,展示如何从图像中获取主色调:
import 'package:flutter/material.dart';
import 'package:spectrum/spectrum.dart';
import 'dart:ui' as ui;
class ColorAnalysisPage extends StatefulWidget {
  @override
  _ColorAnalysisPageState createState() => _ColorAnalysisPageState();
}
class _ColorAnalysisPageState extends State<ColorAnalysisPage> {
  Color? dominantColor;
  Future<void> analyzeImage() async {
    // 加载图像
    final image = await loadImage('assets/sample_image.jpg');
    // 使用 Spectrum 分析图像
    final spectrum = Spectrum.fromImage(image);
    // 获取主色调
    final color = await spectrum.getDominantColor();
    setState(() {
      dominantColor = color;
    });
  }
  Future<ui.Image> loadImage(String assetPath) async {
    final data = await rootBundle.load(assetPath);
    final bytes = data.buffer.asUint8List();
    final codec = await ui.instantiateImageCodec(bytes);
    final frame = await codec.getNextFrame();
    return frame.image;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Color Analysis with Spectrum'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (dominantColor != null)
              Container(
                width: 100,
                height: 100,
                color: dominantColor,
              ),
            ElevatedButton(
              onPressed: analyzeImage,
              child: Text('Analyze Image'),
            ),
          ],
        ),
      ),
    );
  }
}
3. 获取调色板
除了主色调,你还可以从图像中获取调色板:
final palette = await spectrum.getPalette();
        
      
            
            
            
