如何根据背景更改文本颜色,以使两种颜色之间具有良好的对比度

时间:2019-10-17 12:07:06

标签: flutter dart flutter-layout

@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
      ),
    ),
  );
}

输出(backgroundColor:Colors.orange,文本可见):

enter image description here

输出(backgroundColor:Colors.black,文本不可见):

enter image description here

1 个答案:

答案 0 :(得分: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。