要讓控制項產生陰影,最靈活的方式是繼承後覆寫 drawRect:,在實際繪製圖片之前設定 CGContext 的陰影參數。以下以 UIButton 為例。
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface ShadowButton : UIButton {
UIColor *shadowColor;
}
@property(nonatomic, strong) UIColor *shadowColor;
@end
#import "ShadowButton.h"
@implementation ShadowButton
@synthesize shadowColor;
-(void)setProperty {
self.imageEdgeInsets = UIEdgeInsetsMake(0, -1, 3, 2);
self.shadowColor = [UIColor grayColor];
}
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self setProperty];
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect frame = rect;
UIEdgeInsets insets = self.imageEdgeInsets;
frame.origin.x += insets.left;
frame.origin.y += insets.top;
frame.size.width -= (insets.left + insets.right);
frame.size.height -= (insets.top + insets.bottom);
if (shadowColor) {
CGContextSetShadowWithColor(context,
CGSizeMake(insets.right, insets.bottom),
10,
[shadowColor CGColor]);
}
UIImage *image = self.imageView.image;
[image drawInRect:frame];
}
@end
drawRect: 中的流程是:先取得目前的繪圖上下文,依 imageEdgeInsets 把要繪製的矩形往內縮,然後用 CGContextSetShadowWithColor 設定陰影的偏移量、模糊半徑與顏色,最後才把圖片畫進去。由於陰影是在繪圖之前設定的,畫上去的影像自然會帶著陰影。
imageEdgeInsets 在這裡同時扮演兩個角色:既是圖片的內縮邊距,也決定了陰影的偏移方向與距離(insets.right 當 x 偏移、insets.bottom 當 y 偏移),等於用一組數值統一管理兩件事。
如果不需要那麼細緻的控制,直接在 layer 上設定即可,程式碼短得多且效能更好:
button.layer.shadowColor = [UIColor grayColor].CGColor;
button.layer.shadowOffset = CGSizeMake(2, 3);
button.layer.shadowRadius = 5.0;
button.layer.shadowOpacity = 0.8;
兩者的差別在於:layer 陰影由系統合成,不需要重繪;drawRect: 方案是自己畫,能對「只幫圖片加陰影、不加在背景上」這類需求做精細控制。另外要留意 Apple 對 drawRect: 的提醒——除非真的需要自繪,否則留空的覆寫反而會拖慢動畫效能。