一、应用场景
在开发相机相关应用,如图片裁剪,二维码时,我们经常需要在最上层覆盖一层遮罩,如下图:
一个通常的做法(以上图为例),是将界面划分成几个部分,分别绘制,如阴影部分,分上下左右四个部分,然后分别绘制这四个部分,再绘制绿色边框。实现也不难,但太过于繁琐,现在给出一个更简单的方法
#import <UIKit/UIKit.h>
@interface ILMaskView : UIView
@property (unsafe_unretained, nonatomic)CGRect cropRect;
@property (strong, nonatomic) UIColor *borderColor;
@end
#import "ILMaskView.h"
#define kMaskViewBorderWidth 2.0f
@interface ILMaskView ()
@end
@implementation ILMaskView
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(ctx, 0, 0, 0, 0.6);
CGContextFillRect(ctx, self.bounds);
CGContextSetStrokeColorWithColor(ctx, self.borderColor.CGColor);
CGContextStrokeRectWithWidth(ctx, _cropRect, kMaskViewBorderWidth);
CGContextClearRect(ctx, _cropRect);
}
@end