You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为UIVisualEffectView添加阴影与圆角并优化模糊效果?

解决模糊容器阴影削弱模糊效果的方案

你的问题出在containerShadowView直接放在模糊视图下方,不透明的阴影层会遮挡模糊视图本该模糊的底层内容,导致模糊效果被削弱。下面是两种可行的优化方案:

方案一:使用中间容器承载阴影与模糊视图

创建一个中间容器视图,将阴影添加到这个容器的layer上,再把UIVisualEffectView作为子视图添加到容器中,通过模糊视图的clipsToBounds实现圆角。这样阴影在最底层,不会遮挡模糊视图的模糊效果。

代码修改:

.h 文件

@property (strong) UIView *shadowContainerView; // 新增中间容器
@property (strong) UIVisualEffectView *containerView;

.m 文件

- (instancetype)init {
    if (self = [super init]) {
        // 初始化中间阴影容器
        self.shadowContainerView = [[UIView alloc] init];
        self.shadowContainerView.layer.masksToBounds = NO;
        self.shadowContainerView.layer.shadowRadius = 80.0;
        self.shadowContainerView.layer.shadowColor = [[UIColor blackColor] CGColor];
        self.shadowContainerView.layer.shadowOffset = CGSizeZero;
        self.shadowContainerView.layer.shadowOpacity = 0.25;
        [self addSubview:self.shadowContainerView];
        
        // 初始化模糊视图
        self.containerView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
        self.containerView.clipsToBounds = YES;
        self.containerView.layer.cornerRadius = 20.0;
        [self.shadowContainerView addSubview:self.containerView]; // 添加到中间容器
    }
    return self;
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    
    // 设置模糊视图的frame
    CGRect containerFrame = CGRectMake(20.0, 200.0, 380, 480);
    self.containerView.frame = containerFrame;
    
    // 中间容器的frame与模糊视图一致,同时设置shadowPath
    self.shadowContainerView.frame = containerFrame;
    self.shadowContainerView.layer.shadowPath = [[UIBezierPath bezierPathWithRoundedRect:self.shadowContainerView.bounds cornerRadius:self.containerView.layer.cornerRadius] CGPath];
}

方案二:调整阴影的混合模式与透明度

如果不想新增容器,可以修改containerShadowView的图层混合模式,让阴影和底层内容混合后不影响模糊效果:

// 在初始化containerShadowView时添加
self.containerShadowView.layer.compositingFilter = @"multiplyBlendMode";
// 或者降低阴影的不透明度,同时调整颜色的透明度
self.containerShadowView.layer.shadowColor = [[UIColor colorWithWhite:0 alpha:0.15] CGColor];

不过这种方案的效果不如方案一稳定,推荐优先使用方案一。

内容的提问来源于stack exchange,提问作者Vulkan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:27:48