Flutter开发: 实现加载图片提取颜色渐变动画

1,926 阅读1分钟

src=http___pic2.zhimg.com_v2-bc0c14278ec0e2c604f9307a5323815b_1200x500.jpg&refer=http___pic2.zhimg.jpg

一、加载图片提取颜色实现渐变动画

提取图片颜色

说起提取图片颜色,以一个Android的开发者来说,是最熟悉不过的Paltte---调色板,如下:

 Palette.from(bitmap).generate()

那么到了Flutter我们又有哪个类似的框架,那就是palette_generator

PaletteGenerator.fromImage(ui.Image image,Rect region,.....)

而我们导入只需要在pubspec.yaml中导入:palette_generator: ^0.3.0 即可

二、效果图(Gif)

效果图

三、采样逻辑

    var rectWidth = image.width / 3.0;
    var rectHeight = image.height / 3.0;
    var color = await PaletteGenerator.fromImage(image,
        region: Rect.fromCenter(
            center: Offset(image.width / 2.0, image.height / 2.0),
            width: rectWidth,
            height: rectHeight),
        maximumColorCount: 5)
        

通过获取加载后图片的尺寸,从中间开始取裁剪区域,长宽各为图片长宽的三分之一。
通过Stack控件进行两层交替进行渐变实现动画效果。


Stack(
      children: [
        AnimatedOpacity(
          opacity: _placeVisible ? 1.0 : 0.15,
          curve: Curves.easeOut,
          duration: Duration(milliseconds: widget.duration),
          child: Container(
            width: widget.imageWidth,
            height: widget.imageHeight,
            color: _placeColor,
          ),
        ),
        FadeTransition(
          opacity: _curvedAnimation,
          child: SizedBox(
              width: widget.imageWidth,
              height: widget.imageHeight,
              child: Image(
                width: widget.imageWidth,
                height: widget.imageHeight,
                image: _imageProvider,
                fit: widget.fit,
              )),
        )
      ],
    )

四、Github地址

项目的代码已经提交到Github: 仓库地址
欢迎大家留言,如果觉得好的人多,可以考虑做成库,提交到Pub