Flutter实现图片四边缘渐变淡出(透明渐变)效果
在Flutter中为图片添加四边缘透明渐变效果
要实现图片四周向中间渐变透明、与背景自然融合的效果,有两种常用的实现方式,以下是具体代码和说明:
方法一:Stack叠加渐变遮罩层
这种方式直观易懂,可单独调整每个边缘的渐变范围和颜色:
Stack( alignment: Alignment.center, children: [ // 目标图片 Image.network( 'https://example.com/your-image.jpg', fit: BoxFit.cover, width: double.infinity, height: double.infinity, ), // 顶部渐变层(替换Colors.white为你的背景色) Container( height: 40, // 渐变高度,按需调整 decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.white, Colors.transparent], ), ), ), // 底部渐变层 Align( alignment: Alignment.bottomCenter, child: Container( height: 40, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [Colors.white, Colors.transparent], ), ), ), ), // 左侧渐变层 Align( alignment: Alignment.centerLeft, child: Container( width: 40, // 渐变宽度,按需调整 decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [Colors.white, Colors.transparent], ), ), ), ), // 右侧渐变层 Align( alignment: Alignment.centerRight, child: Container( width: 40, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.centerRight, end: Alignment.centerLeft, colors: [Colors.white, Colors.transparent], ), ), ), ), ], )
注意事项:
- 将
Colors.white替换为图片所在区域的实际背景色 - 调整
height/width参数控制渐变的范围 - 根据需求修改图片的
fit属性(如BoxFit.contain等)
方法二:ShaderMask实现一体化渐变
这种方式更高效,无需多个容器嵌套,通过遮罩直接让图片边缘渐变透明,适配任意背景:
ShaderMask( shaderCallback: (Rect bounds) { // 处理上下方向的渐变 return LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.transparent, Colors.black, Colors.black, Colors.transparent], stops: [0, 0.1, 0.9, 1], // 0.1和0.9控制渐变范围,数值越小渐变越宽 ).createShader(bounds); }, blendMode: BlendMode.dstIn, // 仅保留遮罩不透明区域的图片内容 child: ShaderMask( shaderCallback: (Rect bounds) { // 处理左右方向的渐变 return LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [Colors.transparent, Colors.black, Colors.black, Colors.transparent], stops: [0, 0.1, 0.9, 1], ).createShader(bounds); }, blendMode: BlendMode.dstIn, child: Image.network( 'https://example.com/your-image.jpg', fit: BoxFit.cover, width: double.infinity, height: double.infinity, ), ), )
注意事项:
- 修改
stops数组中的数值调整渐变宽度(比如将0.1改为0.05会让渐变范围更宽) - 若需要更平滑的过渡效果,可增加颜色节点和对应的stop值
内容的提问来源于stack exchange,提问作者josue.0
相关产品推荐
相关产品推荐

