首页 文章

iOS6将阴影添加到具有角半径的容器UIView

提问于
浏览
1

包含UIView如何同时具有阴影和圆角半径?

我曾多次尝试在SO上提出的其他解决方案,但不幸的是它们似乎不适用于iOS6(或者至少不适用于我)

所以我想我可能发布这个,以便找到iOS6解决方案 .

我有一个容器 UIView ,其中包含两个子视图

- a custom UIImageView
- a custom UIView

我希望整个UIView的圆角半径为2.5,但我也希望UIView有一个阴影 . However, so far, I get only 1 of these 2 desires, never both at the same time.

这是我的代码,我使用SO解决方案的不同尝试有不同的版本,但这只是我的一个版本 .

self.layer.shouldRasterize = YES;
    self.layer.rasterizationScale = [UIScreen mainScreen].scale;
    self.layer.cornerRadius = 2.5;
    self.layer.masksToBounds = YES;
    self.layer.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.1].CGColor; //0.1
    self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
    self.layer.shadowOpacity = 1.0;
    self.layer.shadowRadius = 3.0;

^这里 self 是包含上面描述的两个子视图的自定义UIView

有谁知道这个问题的iOS6解决方案?


UPDATE

所以,我不需要边框颜色,所以当我看到解决方案时我没有添加它,但这次我添加了,使用下面评论中的解决方案,似乎UIView正在变得圆润,但我真的想要结合使用UIImageView和UIView .

基本上,UIImageView位于顶部,UIView位于底部 .

那么我如何才能使UIImageView的顶部被舍入,并且只有UIView的底部被舍入 .

谢谢 .

Note: shadows work as one whole object, but the corner radius is not working as one whole object?

2 回答

  • 2

    我想到了 .

    self.layer.shouldRasterize = YES;
    self.layer.rasterizationScale = [UIScreen mainScreen].scale;
    self.layer.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.8].CGColor;
    self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.layer.bounds cornerRadius:self.layer.cornerRadius].CGPath;
    self.layer.shadowOpacity = 1.0;
    self.layer.shadowRadius = 3.0;
    
    UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    [self addSubview:container];
    
    [container addSubview:self.someCustomUIView];
    [container addSubview:self.someCustomImageView];
    
    container.layer.cornerRadius = 2.5;
    container.layer.masksToBounds = YES;
    

    所以基本上:

    • 我设置了主UIView的阴影 .

    • 我创建了一个容器子视图,其中包含另外两个子视图

    • 我设置了容器子视图的角半径

    • 瞧!有用!

    • 我希望这适用于在一个UIView中有多个子视图的其他人

    • 我要感谢大家的帮助 . :)

  • 5

    我想你应该改变这行代码:

    self.layer.masksToBounds = YES;
    

    对这一个

    self.layer.masksToBounds = NO;
    

    如果将masksToBounds设置为YES,那么您将看不到超出视图边界的任何内容,这就是阴影的情况 .

    此代码来自我当前的项目(iOS 6),它工作正常 . 我可以看到圆角和阴影 .

    self.layer.masksToBounds = NO;
    self.layer.cornerRadius = 5.0;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(0, -1);
    self.layer.shadowOpacity = 0.6;
    
    UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect: self.layer.bounds];
    self.layer.shadowPath = shadowPath.CGPath;
    

相关问题