2011-10-06 67 views
3
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的参考资料,但没有得到任何线索。当设置shadowPath时,UIImageView的阴影变得比预期的大阴影

+0

我得到同样的结果努力使一类方法上的UIView添加阴影。 – user

回答

0

这可能是因为UIViewbounds还不是真正的。 (在awakeFromNibviewDidLoad等)

等待视图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 
    } 
}