likes
comments
collection
share

Flutter App开发黑白化UI实现方案ColorFiltered

作者站长头像
站长
· 阅读数 10

一、相信大家对App黑白化并不陌生,经常可以看到大厂的App在一定的时候会呈现黑白样式如下:

Flutter App开发黑白化UI实现方案ColorFiltered Flutter App开发黑白化UI实现方案ColorFiltered

这种效果在原生开发上大家肯定或多或少都了解过,原理都是在根布局绘制的时候将画笔饱和度设置成0;具体实现大家可以搜一搜这里就不贴了。

二、下面就来说说在Flutter这一侧需要怎么实现

  • 原理和原生还是一样都是将饱和度设置成0,不过在Flutter这实现起来会比在原生更加的简单。
  • Flutter直接为我们提供了ColorFiltered组件(以Color作为源的混合模式Widget)。
  • 只需要将ColorFiltered做为根组件(包裹MaterialApp)即可改变整个应用的颜色模式。

实现的最终代码如下

class SaturationWidget extends StatelessWidget {
  final Widget child;

  ///value [0,1]
  final double saturation;

  const SaturationWidget({
    required this.child,
    this.saturation = 0,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ColorFiltered(
      colorFilter: ColorFilter.matrix(_saturation(saturation)),
      child: child,
    );
  }

  ///Default matrix
  List<double> get _matrix => [
        1, 0, 0, 0, 0, //R
        0, 1, 0, 0, 0, //G
        0, 0, 1, 0, 0, //B
        0, 0, 0, 1, 0, //A
      ];

  ///Generate a matrix of specified saturation
  ///[sat] A value of 0 maps the color to gray-scale. 1 is identity.
  List<double> _saturation(double sat) {
    final m = _matrix;
    final double invSat = 1 - sat;
    final double R = 0.213 * invSat;
    final double G = 0.715 * invSat;
    final double B = 0.072 * invSat;
    m[0] = R + sat;
    m[1] = G;
    m[2] = B;
    m[5] = R;
    m[6] = G + sat;
    m[7] = B;
    m[10] = R;
    m[11] = G;
    m[12] = B + sat;
    return m;
  }
}
  • 通过4x5的R、G、B、A、颜色矩阵来生成一个colorFilter
  • 最终通过饱和度的值来计算颜色矩阵(饱和度计算算法从Android原生copy过来的)这样就轻松实现了整个App的黑白化(不过iOS的webview是不支持的)

三、最后来看下实现的效果

Flutter App开发黑白化UI实现方案ColorFiltered