美文网首页FlutterFlutter学习
Flutter Image透明渐变

Flutter Image透明渐变

作者: _安迪_ | 来源:发表于2021-07-27 16:58 被阅读0次

有个设计需求,需要图片往一个方向线性渐变,自己研究了一下,需要用到ShaderMask这个遮罩,它除了可以添加颜色渐变,也可以实现透明度渐变,有兴趣的小伙伴可以自行了解,这里贴一下我封装的图片透明度渐变工具类,支持自定义渐变方向、本地图片和网络图片(网络图片加载需要依赖cached_network_image),
效果如下:


下面是原图,上面是透明渐变

代码:

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

/// 透明渐变的图片Widget
class GradientImage extends StatelessWidget {
  /// 图片地址-支持本地和网络图片
  final String imgName;

  /// 图片宽度
  final double? width;

  /// 图片高度
  final double? height;

  /// 渐变开始位置 - 默认Alignment.topCenter
  final AlignmentGeometry begin;

  /// 渐变结束位置 - 默认Alignment.bottomCenter
  final AlignmentGeometry end;
  const GradientImage(
      {Key? key,
      required this.imgName,
      this.width,
      this.height,
      this.begin = Alignment.topCenter,
      this.end = Alignment.bottomCenter})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ShaderMask(
      shaderCallback: (rect) {
        return LinearGradient(
          begin: begin,
          end: end,
          colors: [Colors.black, Colors.transparent],
        ).createShader(Rect.fromLTRB(0, 0, rect.width, rect.height));
      },
      blendMode: BlendMode.dstIn,
      child: _createImage(),
    );
  }

  /// 根据图片名判断是网络还是本地的图片
  Widget _createImage() {
    if (imgName.startsWith('http')) {
      return CachedNetworkImage(
          width: width,
          height: height,
          imageUrl: imgName,
          fit: BoxFit.cover);
    } else {
      return Image.asset(imgName,
          width: width,
          height: height,
          fit: BoxFit.cover,
          alignment: Alignment.topCenter);
    }
  }
}

相关文章

网友评论

    本文标题:Flutter Image透明渐变

    本文链接:https://www.haomeiwen.com/subject/mluomltx.html