简体   繁体   English

UIView 阴影和圆角

[英]UIView shadow AND rounded corners

I have a UIView which I want to have a shadow and round corners.我有一个 UIView,我想要一个阴影和圆角。 The problem is - a shadow requires masksToBounds = NO while round corners requires masksToBounds = YES .问题是 - 阴影需要masksToBounds = NO而圆角需要masksToBounds = YES

The solution I found is to have a container which will have shadow and add my UIView as a subview of the container - and give it rounded corners.我找到的解决方案是拥有一个带有阴影的容器,并将我的 UIView 添加为容器的子视图 - 并给它圆角。

This works.这有效。 I have both shadow AND round corners - but it's no good.我有阴影和圆角 - 但这不好。 The shadow is of a rectangle view and my image has rounded corners.阴影是矩形视图,我的图像有圆角。

阴影和圆角

How can I implement a shadow for the rounded corners?如何为圆角实现阴影?

import UIKit

@IBDesignable
class customButton: UIView {

    @IBInspectable var cornerRadius:CGFloat = 0{
        didSet{
            self.layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var borderWidth:CGFloat = 0{
        didSet{
            self.layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor:UIColor = UIColor.white{
        didSet{
            self.layer.borderColor = borderColor.cgColor
        }
    }


}

Set this as class for the UIView and put maskToBound = true .将此设置为 UIView 的类并放置maskToBound = true Then in the inspector set the value accordingly to get a rounded shadow.然后在检查器中相应地设置值以获得圆形阴影。

Remove the container, its clipping your view shadow.移除容器,它会裁剪您的视图阴影。 Import QuartzCore/QuartzCore.h .导入QuartzCore/QuartzCore.h And try this code to your view并尝试将此代码用于您的视图

#import < QuartzCore/QuartzCore.h>

...

view.layer.cornerRadius = 5.0f;
[view.layer setShadowColor:[UIColor redColor].CGColor];
[view.layer setShadowOpacity:0.7];
[view.layer setShadowRadius:5.0];
[view.layer setShadowOffset:CGSizeMake(2.0, 2.0)];

to know more about maskToBound see this link要了解有关 maskToBound 的更多信息,请参阅此链接

What UIView layer.masksToBounds is doing if set to YES? 如果设置为 YES,UIView layer.masksToBounds 正在做什么?

// border radius
[yourView.layer setCornerRadius:30.0f];

// border
[yourView.layer setBorderColor:[UIColor blackColor].CGColor];
[yourView.layer setBorderWidth:1.5f];
 yourView.layer.masksToBounds=YES;

// drop shadow
[yourView.layer setShadowColor:[UIColor lightGrayColor].CGColor];
[yourView.layer setShadowOpacity:0.8];
[yourView.layer setShadowRadius:3.0];
[yourView.layer setShadowOffset:CGSizeMake(2.0, 2.0)];

This may help you.这可能对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM