在UIImageView分類里添加方法
@implementation UIImageView (custom)
//設(shè)置圓角
- (void)setImageCornerRadius: (CGFloat)radius {
self.layer.cornerRadius = radius;
// ios9之后對imageview設(shè)置不會觸發(fā)離屏渲染
self.layer.masksToBounds = YES;
}
//設(shè)置陰影
- (void)setShadowWithColor:(UIColor *)color shadowXOffset:(CGFloat)xOffset
shadowYOffset:(CGFloat)yOffset
shadowRadius:(CGFloat)radius
shadowOpacity:(CGFloat)opacity{
if (self.superview == nil) {
NSLog(@"WRNING: a parent view of the image view is necessary to add a shadow view.");
return;
}
//shadowContainer 為在imageview的父view中加的 設(shè)置陰影的view
if (self.shadowContainer != nil) {
[self.shadowContainer removeFromSuperview];
}
self.shadowContainer = [[UIView alloc] initWithFrame: self.frame];
self.shadowContainer.userInteractionEnabled = NO;
self.shadowContainer.backgroundColor = [UIColor whiteColor];
self.shadowContainer.layer.shadowColor = color.CGColor;
self.shadowContainer.layer.shadowOffset = CGSizeMake(xOffset, yOffset);
self.shadowContainer.layer.shadowRadius = radius;
self.shadowContainer.layer.shadowOpacity = opacity;
self.shadowContainer.layer.cornerRadius = self.layer.cornerRadius;
//必加該句 直接向Core Animation提供陰影形狀,通過調(diào)用setShadowPath來提供一個CGPath給視圖的Layer,(CGPath為任意你想生成的陰影的形狀),可以防止離屏渲染
self.shadowContainer.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:radius].CGPath;
self.shadowContainer.clipsToBounds = NO;
[self.superview insertSubview:self.shadowContainer atIndex:0];
}
@end