如何从flutter中的十六进制代码获取颜色名称?

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

我正在尝试从十六进制代码中检索颜色名称。我正在使用一种方法,从相机捕获图像并成功从这些图像中提取十六进制代码。但是,我很难准确确定相应的颜色名称。

我使用此代码获取颜色名称和十六进制代码: `Future _getImageAndPickColor() 异步 {

final pickedFile =
    await ImagePicker().pickImage(source: ImageSource.camera);
if (mounted) {
  Navigator.pop(context);
}

if (pickedFile != null) {
  
  final bytes = await pickedFile.readAsBytes();
  final image = img.decodeImage(Uint8List.fromList(bytes));

  final pixelColor = image!.getPixel(image.width ~/ 2, image.height ~/ 2);

  
    final red = pixelColor.r;
    final green = pixelColor.g;
    final blue = pixelColor.b;

    _pickedColor =
        Color.fromRGBO(red.toInt(), green.toInt(), blue.toInt(), 1);

    _hexCode = _pickedColor.value.toRadixString(16).padLeft(8, '0').substring(2);

    colorName(_hexCode);
   
  
      _searching.text = _colorName;
      print('colorName $_colorName');
      print('hexcode $_hexCode');
      searchFilter(_hexCode);

    //showMyDialogForCamera(context);
} 

} `

flutter dart colors
1个回答
0
投票

就像评论者已经提到的那样,您可以尝试从给定的集合中找到最接近的颜色。您可以将 RGB 空间视为 3 维空间,并使用平方和的简单平方根来获得欧氏距离,如下所示:

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

double distance(Color a, Color b) {
  return sqrt(
    pow(a.red - b.red, 2) + 
    pow(a.green - b.green, 2) + 
    pow(a.blue - b.blue, 2)
  );
}

使用此功能,您可以通过将集合中的每种颜色与该颜色进行比较来找到最接近的颜色

const colors = [Colors.red, Colors.pink, Colors.lightGreen, Colors.orange];

const myColor = Color(0xffaa00ee);

var minDistance = double.maxFinite;
Color? closestColor = colors.first;

for (final color in colors) {
  final currentDistance = distance(color, myColor);
  if (currentDistance  < minDistance) {
    // it is closer! Use this one for now
    closestColor = color;
    minDistance = currentDistance;
  }
}
print('Closest is $closestColor');
© www.soinside.com 2019 - 2024. All rights reserved.