然后重写drawRect:方法,为scanView绘制边框和四角:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
// 绘制白色边框
CGContextAddRect(context, self.bounds);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetLineWidth(context, 2.0);
CGContextStrokePath(context);
// 绘制四角:
CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
CGContextSetLineWidth(context, 5.0);
// 左上角:
CGContextMoveToPoint(context, 0, 30);
CGContextAddLineToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 30, 0);
CGContextStrokePath(context);
// 右上角:
CGContextMoveToPoint(context, self.bounds.size.width - 30, 0);
CGContextAddLineToPoint(context, self.bounds.size.width, 0);
CGContextAddLineToPoint(context, self.bounds.size.width, 30);
CGContextStrokePath(context);
// 右下角:
CGContextMoveToPoint(context, self.bounds.size.width, self.bounds.size.height - 30);
CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height);
CGContextAddLineToPoint(context, self.bounds.size.width - 30, self.bounds.size.height);
CGContextStrokePath(context);
// 左下角:
CGContextMoveToPoint(context, 30, self.bounds.size.height);
CGContextAddLineToPoint(context, 0, self.bounds.size.height);
CGContextAddLineToPoint(context, 0, self.bounds.size.height - 30);
CGContextStrokePath(context);
}
如果希望在扫描过程中看到刚才绘制的扫描框,还需要切换到ViewController.m文件,在startStopAction:方法中添加下面的代码来显示扫描框:
- (IBAction)startStopAction:(id)sender
{
if (!self.isReading) {
...
[self.view bringSubviewToFront:self.toolBar]; // display toolBar
[self.view bringSubviewToFront:self.scanView]; // display scanView
...
}
...
}
现在运行,你会看到下面的效果:

接下来我们继续添加扫描线。
首先在ScanView.h文件的接口部分声明一个NSTimer对象的属性:
@property (nonatomic, strong) NSTimer *timer;
然后切换到ScanView.m文件,在实现部分添加loadScanLine方法及代码,并在initWithCoder:方法中调用:
- (void)loadScanLine
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 1.0)];
lineView.backgroundColor = [UIColor greenColor];
[self addSubview:lineView];
[UIView animateWithDuration:3.0 animations:^{
lineView.frame = CGRectMake(0, self.bounds.size.height, self.bounds.size.width, 2.0);
} completion:^(BOOL finished) {
[lineView removeFromSuperview];
}];
}];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
...
if (self) {
...
[self loadScanLine];
}
...
}










