ios 如何为圆 UIImageView 或 UIView 添加阴影?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18403578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:50:41  来源:igfitidea点击:

How can I add shadow to a circle UIImageView or UIView?

iosuiviewuiimageviewcalayershadow

提问by Newbie

I am trying to make a circle UIImageView, and it works. Below is the way I use to make it:

我正在尝试制作一个圆UIImageView,并且它有效。下面是我用来制作它的方法:

[self.pic.layer setMasksToBounds:YES];
[self.pic.layer setCornerRadius:50.0];

I would like to add some shadow to the UIImageView. The below code does add some shadow to my image view, however, the image view changes back to square shape. Can someone give me some pointers to solve this problem? Below is the code I use to add the shadow:

我想为UIImageView. 下面的代码确实为我的图像视图添加了一些阴影,但是,图像视图变回了方形。有人可以给我一些建议来解决这个问题吗?下面是我用来添加阴影的代码:

self.pic.layer.shadowColor = [UIColor purpleColor].CGColor;
self.pic.layer.shadowOffset = CGSizeMake(0, 1);
self.pic.layer.shadowOpacity = 1;
self.pic.layer.shadowRadius = 1.0;
self.pic.clipsToBounds = NO;

回答by Amar

Use the CALayer's shadowPathpropertyand add a UIBezierPathwith rounded rect

使用CALayer'sshadowPath属性并添加一个UIBezierPath带圆角的矩形

self.pic.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.pic.frame cornerRadius:50.0].CGPath;

EDIT

编辑

For a square-ish image view this technique does not work directly because, as you said, the image view goes back to square. Reason: You set clipsToBounds = NOto show the shadow which removes the clipping for corner radius, where imageViewis subview of container.

对于方形图像视图,此技术不能直接工作,因为正如您所说,图像视图会返回方形。原因:您设置clipsToBounds = NO为显示删除角半径剪裁的阴影,其中imageView是 的子视图container

Workaround:
Add your imageview in a container view and then apply the layer shadow to this container. Following is the code I tried.

解决方法:
在容器视图中添加您的图像视图,然后将图层阴影应用于此容器。以下是我试过的代码。

[self.imageView.layer setCornerRadius:60.0];
[self.imageView.layer setMasksToBounds:YES];
self.imageView.clipsToBounds = YES;

self.container.backgroundColor = [UIColor clearColor];
self.container.layer.shadowColor = [UIColor blackColor].CGColor;
self.container.layer.shadowOffset = CGSizeMake(5,15);
self.container.layer.shadowOpacity = 0.5;
self.container.layer.shadowRadius = 2.0;
self.container.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.container.bounds cornerRadius:100.0].CGPath;

The resultant effect is as shown in the screenshot,

产生的效果如截图所示,

enter image description here

在此处输入图片说明

Hope that helps!

希望有帮助!

回答by Arsonik

Without a container but with a background view here is my 2 cents

没有容器但有背景视图,这是我的 2 美分

As a swift 2.2 extension

作为 swift 2.2 扩展

    image?.applyCircleShadow(5, shadowOpacity: 1)
extension UIView {
    func applyCircleShadow(shadowRadius: CGFloat = 2,
                           shadowOpacity: Float = 0.3,
                           shadowColor: CGColor = UIColor.blackColor().CGColor,
                           shadowOffset: CGSize = CGSize.zero) {
        layer.cornerRadius = frame.size.height / 2
        layer.masksToBounds = false
        layer.shadowColor = shadowColor
        layer.shadowOffset = shadowOffset
        layer.shadowRadius = shadowRadius
        layer.shadowOpacity = shadowOpacity
    }
}
extension UIImageView {
    override func applyCircleShadow(shadowRadius: CGFloat = 2,
                                    shadowOpacity: Float = 0.3,
                                    shadowColor: CGColor = UIColor.blackColor().CGColor,
                                    shadowOffset: CGSize = CGSize.zero) {

        // Use UIImageView.hashvalue as background view tag (should be unique)
        let background: UIView = superview?.viewWithTag(hashValue) ?? UIView()
        background.frame = frame
        background.backgroundColor = backgroundColor
        background.tag = hashValue
        background.applyCircleShadow(shadowRadius, shadowOpacity: shadowOpacity, shadowColor: shadowColor, shadowOffset: shadowOffset)
        layer.cornerRadius = background.layer.cornerRadius
        layer.masksToBounds = true
        superview?.insertSubview(background, belowSubview: self)
    }
}

回答by Tung Fam

In case anyone looks for Swift 3 or 4 workingsolution:

如果有人在寻找Swift 3 或 4 工作解决方案:

    let imageSize: CGFloat = 64.0

    // Create a container which has a shadow
    let imageCotainer = UIView(frame: CGRect(x: 0, y: 0, width: imageSize, height: imageSize))
    imageCotainer.clipsToBounds = false
    imageCotainer.layer.shadowColor = UIColor.black.cgColor
    imageCotainer.layer.shadowOpacity = 0.2
    imageCotainer.layer.shadowOffset = CGSize(width: 0, height: 1)
    imageCotainer.layer.shadowRadius = 2

    // Create an image view that will be inserted into the container view
    let imageView = UIImageView(frame: imageCotainer.bounds)
    imageView.image = yourImage
    imageView.clipsToBounds = true
    let cornerRadius = imageView.frame.height / 2
    imageView.layer.cornerRadius = cornerRadius

    // Draw a shadow
    imageCotainer.layer.shadowPath = UIBezierPath(roundedRect: imageCotainer.bounds, cornerRadius: cornerRadius).cgPath
    // Add image into container
    imageCotainer.addSubview(imageView)

Sometimes you also need to set constraints for image inside of the container, but it may work without it too in some cases. But if it's not, add this:

有时您还需要为容器内的图像设置约束,但在某些情况下它也可以在没有它的情况下工作。但如果不是,请添加以下内容:

    // Set constraints for the image inside the container view
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.topAnchor.constraint(equalTo: imageCotainer.topAnchor).isActive = true
    imageView.leftAnchor.constraint(equalTo: imageCotainer.leftAnchor).isActive = true
    imageView.rightAnchor.constraint(equalTo: imageCotainer.rightAnchor).isActive = true
    imageView.bottomAnchor.constraint(equalTo: imageCotainer.bottomAnchor).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: imageSize).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: imageSize).isActive = true

回答by Paul Bénéteau

I created custom classes (swift 3 or 4) and it works very well :

我创建了自定义类(swift 3 或 4)并且效果很好:

class RoundShadowImageView: RoundView {

    var imageView = RoundImageView()

    var image: UIImage!  {
        didSet {
            imageView.image = image
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(imageView)
        needsUpdateConstraints()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addSubview(imageView)
        needsUpdateConstraints()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        clipsToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.1
        layer.shadowOffset = CGSize(width: 0, height: 10)
        layer.shadowRadius = 10
        layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: frame.height / 2.0).cgPath
    }

    override func updateConstraints() {
        super.updateConstraints()

        imageView.snp.makeConstraints { (make) -> Void in
            make.height.width.equalTo(self)
            make.center.equalTo(self)
        }
    }
}

class RoundImageView: UIImageView {

    override func layoutSubviews() {
        super.layoutSubviews()
        let radius: CGFloat = self.bounds.size.height / 2.0
        layer.cornerRadius = radius
        clipsToBounds = true
    }
}

class RoundView: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()
        let radius: CGFloat = self.bounds.size.height / 2.0
        layer.cornerRadius = radius
        clipsToBounds = true
    }
}

There are 2 classes to make a container and an image view round. And the main class which combines both of them: the one that you'll call.

有 2 个类可以制作容器和图像视图。以及结合了两者的主类:您将调用的类。

回答by Sandeep Singh Rana

I might be a bit late.

我可能有点晚了。

You can easily set the required attributes on the storyboard attribute inspector.

您可以在故事板属性检查器上轻松设置所需的属性。

enter image description here

在此处输入图片说明

The result would be something like this.

结果会是这样的。

Round Image

圆形图像

回答by Nilesh Shinde

extension UIImageView {
    func addShadow() {
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOffset = CGSize(width: 2, height: 5)
        self.layer.shadowOpacity = 0.5
        self.layer.shadowRadius = 1.0
        self.clipsToBounds = false
    }
}
try this code. hope it will help you....