【问题标题】:How to change Text color depending on background so that there is good contrast between the two colors如何根据背景更改文本颜色,以使两种颜色之间形成良好的对比
【发布时间】:2020-02-14 08:31:01
【问题描述】:
@override
Widget build(BuildContext context) {
  var backgroundColor = Colors.orange; // this color could be anything

  return Scaffold(
    body: Center(
      child: Container(
        padding: const EdgeInsets.all(12),
        color: backgroundColor,
        child: Text("Hello World"), // if backgroundColor: Colors.orange this is visible but if backgroundColor: Colors.black, it isn't visible
      ),
    ),
  );
}

输出(背景颜色:Colors.orange,文本可见):

输出(背景颜色:Colors.black,文本不可见):

【问题讨论】:

    标签: flutter dart flutter-layout


    【解决方案1】:

    您可以使用 Color 类的 computeLuminance()。像这样的:

    @override
    Widget build(BuildContext context) {
      var backgroundColor = Colors.orange; // this color could be anything
      var foregroundColor = backgroundColor.computeLuminance() > 0.5 ? Colors.black : Colors.white; 
    
      return Scaffold(
        body: Center(
          child: Container(
            padding: const EdgeInsets.all(12),
            color: backgroundColor,
            child: Text("Hello World", style: TextStyle(color: foregroundColor)), 
          ),
        ),
      );
    }
    

    当然,您需要使用亮度 IF 语句... 1.0 是白色,0.0 是黑色。例如,黄色约为 0.8。

    【讨论】:

    • 请注意,如果使用 alpha 使颜色“变浅”,则此方法不起作用。如果您需要使颜色更浅/更深,请考虑修改 HSL 值:stackoverflow.com/a/58604669/1328576
    猜你喜欢
    • 2016-06-02
    • 2022-10-18
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 2012-02-07
    • 1970-01-01
    相关资源
    最近更新 更多