如何根据背景图片更改文本颜色 - Flutter

Sin*_*afi 14 textcolor dart flutter

我想根据背景图像更改文本(和图标)颜色以提高可见性。

我试过: 使用palette_generator包,检查背景图像的主色,并 从flutter_statusbarcolor包中使用WhiteForgroundForColor函数(返回一个bool)为我的文本(和图标)颜色选择黑色或白色。

问题:有时主色会变成空。在我的测试中,这种情况发生在黑色和白色,我不知道有什么方法可以找出哪一种。

Future<bool> useWhiteTextColor(String imageUrl) async {
  PaletteGenerator paletteGenerator =
      await PaletteGenerator.fromImageProvider(
    NetworkImage(imageUrl),

    // Images are square
    size: Size(300, 300),

    // I want the dominant color of the top left section of the image
    region: Offset.zero & Size(40, 40),
  );

  Color dominantColor = paletteGenerator.dominantColor?.color;

  // Here's the problem 
  // Sometimes dominantColor returns null
  // With black and white background colors in my tests
  if (dominantColor == null) print('Dominant Color null');

  return useWhiteForeground(dominantColor);
}
Run Code Online (Sandbox Code Playgroud)

我找到了其他语言的其他方法,但我不知道在 dart 中实现相同方法的方法。

附加说明:我的实际代码包括一些额外的复杂性。我正在使用 SliverAppBar,在这里我想确定扩展灵活空间时的标题和图标颜色。基于,我在社区的帮助下在崩溃时更改了它们的颜色。

小智 22

颜色类已经有一个计算亮度的方法,称为computeLuminance()

Color textColor = color.computeLuminance() > 0.5 ? Colors.black : Colors.white;
Run Code Online (Sandbox Code Playgroud)

  • 警告:根据computeLuminance(...)文档“计算该值的计算成本很高。” (4认同)

Kam*_*san 6

我使用以下方法找出要使用的方法(黑色或白色)。

Color getTextColor(Color color) {
int d = 0;

// Counting the perceptive luminance - human eye favors green color...
double luminance =
    (0.299 * color.red + 0.587 * color.green + 0.114 * color.blue) / 255;

if (luminance > 0.5)
  d = 0; // bright colors - black font
else
  d = 255; // dark colors - white font

return Color.fromARGB(color.alpha, d, d, d);   }
Run Code Online (Sandbox Code Playgroud)


小智 6

根据卡片或按钮或标签的背景颜色获取文本颜色有两种方法。

第一个是:

Color txColor = color.computeLuminance() < 0.5 ? Colors.white : Colors.black;
Run Code Online (Sandbox Code Playgroud)

第二种是使用主题,用户可能有设备的深色主题或浅色主题。

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

class ColorEstimationPage extends StatelessWidget {
  Color _randomBackgroundColor() {
    List<Color> colors = [Colors.red, Colors.green, Colors.amber, Colors.black];

    return colors[Random().nextInt(colors.length)];
  }
   /// With this you can get the Color either black or white
  Color _textColorForBackground(Color backgroundColor) {
    if (ThemeData.estimateBrightnessForColor(backgroundColor) ==
        Brightness.dark) {
      return Colors.white;
    }

    return Colors.black;
  }

  @override
  Widget build(BuildContext context) {
    Color bgColor = _randomBackgroundColor();
    return Scaffold(
      backgroundColor: bgColor,
      body: Center(
        child: Text(
          "I'm the correct text color!",
          style: TextStyle(color: _textColorForBackground(bgColor)),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)