Flutter中如何设置图片上下部分超出容器显示?
问题描述
想要实现如下设计效果:
但当前代码实现的效果不符合预期,图片位置不对:
我用的代码如下:
Stack( children: [ Container( width: width * 0.9, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), gradient: const LinearGradient( begin: Alignment.centerRight, end: Alignment.bottomLeft, colors: [ AppColors.orangeColorLight, AppColors.orangeColorDark ], ), ), child: Padding( padding: const EdgeInsets.only(left: 20, top: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ customText(context), const SizedBox(height: 10,), getNowBtn() ], ), ), ), Positioned( right: 0, // Adjust this value according to your requirement bottom: 0, // Adjust this value according to your requirement child: Image.asset(MediaConstants.menImage, width: width * 0.49,height: height*0.2,), ), ], );
需要调整代码让图片的上下部分能超出橙色容器。
解决方案
要实现图片上下超出容器的效果,关键改两处:
调整
Positioned的定位参数
把bottom设为负数,再加上top参数也设为负数(数值根据你想要的超出幅度调整),这样图片就能上下都超出橙色容器。给
Stack设置clipBehavior: Clip.none
Stack默认会裁剪掉超出自身范围的内容,必须关闭裁剪才能让图片的超出部分显示出来。
调整后的代码:
Stack( clipBehavior: Clip.none, // 关闭裁剪,允许内容溢出 children: [ Container( width: width * 0.9, // 给容器加最小高度,避免内容过短导致容器高度不够 constraints: const BoxConstraints(minHeight: 180), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), gradient: const LinearGradient( begin: Alignment.centerRight, end: Alignment.bottomLeft, colors: [ AppColors.orangeColorLight, AppColors.orangeColorDark ], ), ), child: Padding( padding: const EdgeInsets.only(left: 20, top: 20, bottom: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ customText(context), const SizedBox(height: 10,), getNowBtn() ], ), ), ], Positioned( right: 0, top: -20, // 图片向上超出的距离 bottom: -20, // 图片向下超出的距离 child: Image.asset(MediaConstants.menImage, width: width * 0.49), ), ), );
额外提示:
- 给Container加最小高度是为了避免文本内容太短时,容器高度不够,导致图片超出效果不稳定,数值可以根据你的UI需求调整。
top和bottom的负值大小可以灵活修改,直到达到你想要的超出效果为止。
内容的提问来源于stack exchange,提问作者user1
相关产品推荐
相关产品推荐

