iphone - 当设置shadowPath时,UIImageView的阴影变得比预期的大

标签 iphone uiimageview calayer shadow

CGRect rect = biggerImageView.bounds;
if([biggerImageView.layer respondsToSelector:@selector(setShadowColor:)])
{
    float shadowOffset = rect.size.width * 0.02;
    biggerImageView.layer.shadowColor = [UIColor colorWithWhite: 0.25 alpha: 0.55].CGColor;
    biggerImageView.layer.shadowOffset = CGSizeMake(shadowOffset, shadowOffset);
    biggerImageView.layer.shadowOpacity = 0.8;
    //      biggerImageView.layer.shadowPath = [UIBezierPath bezierPathWithRect: rect].CGPath;                                                                                                                                                                            
}

注释掉的行导致阴影变得比预期更大。
(顶部和底部垂直较长的阴影)
我查阅了 CALayer 引用资料,但没有任何线索。

最佳答案

这可能是因为 UIView bounds 还不是真正的。 (如awakeFromNibviewDidLoad)

等待 View layoutSubviews 或 viewController viewWillLayoutSubviews 被调用,并在那里更新阴影的路径。

我创建了这个快速扩展来在我需要的任何地方添加相同的阴影(带有 cornerRadius 支持):

import UIKit

extension UIView {
    /// Call this from `layoutSubviews` or `viewWillLayoutSubviews`.
    /// The shadow will be the same color as this view background.
    func layoutShadow() {

        // Update frame
        if let shadowView = superview?.viewWithTag(978654123) {
            shadowView.frame = frame
            shadowView.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
            return
        }

        // Create the shadow the first time
        let shadowView = UIView(frame: frame)
        shadowView.tag = 978654123
        shadowView.translatesAutoresizingMaskIntoConstraints = false
        superview?.insertSubview(shadowView, belowSubview: self)

        shadowView.layer.shadowColor = (backgroundColor ?? UIColor.black).cgColor
        shadowView.layer.shadowOpacity = 0.8
        shadowView.layer.shadowOffset = CGSize(width: -2.0, height: 4.0)
        shadowView.layer.shadowRadius = 4.0
        shadowView.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
    }
}

关于iphone - 当设置shadowPath时,UIImageView的阴影变得比预期的大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7677039/

相关文章:

iphone - 上传图片 iPhone

ios - Swift 给 UIImageView 背景添加透明色

ios - UIView 中的圆角 : CALayer or background Image?

ios - 带有自定义 drawRect 和 animateWithDuration 的 UIView

iphone - 在 iOS 中保存/检索视频文件

iphone - 未读推送通知的生命周期

swift - 如何在 swift 中将 UIImageView load() 函数与completionHandler一起使用

ios - 为什么我的 UIImageView 替换了第二个?

iphone - CALayer shouldRasterize 传播到所有子层吗?

iphone - 在 Swift 中将图像保存在另一个图像之上