【问题标题】:UIImageView's shadow gets bigger than intended when shadowPath is set设置 shadowPath 时 UIImageView 的阴影变得比预期大
【发布时间】:2011-12-02 09:15:07
【问题描述】:
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 上创建一个类别方法来添加阴影时得到了完全相同的结果。

标签: iphone uiimageview calayer shadow


【解决方案1】:

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

等待视图 layoutSubviews 或 viewController viewWillLayoutSubviews 被调用,并在那里更新你的影子路径。

我创建了这个 swift 扩展来在我需要的任何地方添加相同的阴影(支持 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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多