按色调对颜色列表进行排序 (Dart)

问题描述 投票:0回答:1

我有一个 8 位 ARGB 整数颜色列表。看起来像这样。

List<int> listOfColors = [-2350809, -5980676, -8722497, -2380289, -30596, -272549, -18312];

我想在按色调排序的列表中显示这些颜色。意味着例如。所有红色色调(从暗到亮)应依次显示,然后是绿色色调,然后是蓝色色调...

我怎样才能实现这个目标?我尝试将颜色转换为 HSV,但我不知道如何对它们进行排序。

var hsvColor = HSVColor.fromColor(Color(colorInt));

有人能指出我正确的方向吗?

flutter dart sorting colors
1个回答
0
投票

这里有一个如何按色调排序的示例。

  static List<int> sortColorsByHue(List<int> colors) {
    List<Map<String, dynamic>> colorsWithHue = [];

    // Calculate hue for each color
    for (int color in colors) {
      List<double> hsv = argbToHsv(color);
      colorsWithHue.add({'color': color, 'hue': hsv[0]});
    }

    // Sort colors based on hue
    colorsWithHue
        .sort((a, b) => (a['hue'] as double).compareTo(b['hue'] as double));

    // Extract sorted colors
    List<int> sortedColors = [];
    for (var colorData in colorsWithHue) {
      sortedColors.add(colorData['color'] as int);
    }

    return sortedColors;
  }


  // Convert ARGB to HSV
  static List<double> argbToHsv(int argb) {
    double r = ((argb >> 16) & 0xFF) / 255.0;
    double g = ((argb >> 8) & 0xFF) / 255.0;
    double b = (argb & 0xFF) / 255.0;

    double maxChannelValue = max(max(r, g), b);
    double minChannelValue = min(min(r, g), b);
    double delta = maxChannelValue - minChannelValue;

    double h, s;
    double v = maxChannelValue;

    if (delta == 0) {
      h = 0;
      s = 0;
    } else {
      s = delta / maxChannelValue;

      if (r == maxChannelValue) {
        h = (g - b) / delta;
      } else if (g == maxChannelValue) {
        h = 2 + (b - r) / delta;
      } else {
        h = 4 + (r - g) / delta;
      }

      h *= 60;
      if (h < 0) h += 360;
    }

    return [h, s, v];
  }

让我知道它是否适合您。

© www.soinside.com 2019 - 2024. All rights reserved.