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参考文献,但没有得到任何线索。
答案 0 :(得分:0)
这可能是因为UIView
bounds
还不是真正的那个。 (例如awakeFromNib
或viewDidLoad
)
等待调用视图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
}
}