.h文件:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface JSPreView : UIView
@property (nonatomic,strong)AVCaptureSession *session;
@end
.m文件:
#import "JSPreView.h"
@interface JSPreView ()
@property (nonatomic,strong)UIImageView *imageView;
@property (nonatomic,strong)UIImageView *lineImageView;
@property (nonatomic,strong)NSTimer *timer;
@end
@implementation JSPreView
/**
* 重写该方法,将设置视图主layer的创建类型
*
* @return AVCaptureVideoPreviewLayer 特殊的layer 可以展示输入设备采集到得信息
*/
+ (Class)layerClass
{
return [AVCaptureVideoPreviewLayer class];
}
- (void)setSession:(AVCaptureSession *)session
{
_session = session;
AVCaptureVideoPreviewLayer *layer = (AVCaptureVideoPreviewLayer *)self.layer;
layer.session = session;
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[self setUiConfig];
}
return self;
}
- (void)setUiConfig
{
//设置背景图片
_imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pick_bg.png"]];
//设置位置到界面的中间
_imageView.frame = CGRectMake(self.bounds.size.width * 0.5 - 140, self.bounds.size.height * 0.5 - 140, 280, 280);
//添加到视图上
[self addSubview:_imageView];
//初始化二维码的扫描线的位置
_lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 10, 220, 2)];
_lineImageView.image = [UIImage imageNamed:@"line.png"];
[_imageView addSubview:_lineImageView];
//开启定时器
_timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(animation) userInfo:nil repeats:YES];
}
- (void)animation
{
[UIView animateWithDuration:2.8 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
_lineImageView.frame = CGRectMake(30, 260, 220, 2);
} completion:^(BOOL finished) {
_lineImageView.frame = CGRectMake(30, 10, 220, 2);
}];
}
@end
使用演示:
// 4. 预览Layer
// self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
// 添加到当前视图的Layer中
// [self.view.layer addSublayer:self.previewLayer];
// 设置layer的尺寸
// self.previewLayer.frame = self.view.bounds;
JSPreView *preview = [[JSPreView alloc]initWithFrame:self.view.bounds];
preview.session = self.session;
[self.view addSubview:preview];
将创建预览Layer的操作封装在了自定义的View中,因为需要Session,所以在.h文件中提供管理一个对外Session属性.将原有的添加预览Layer操作换成了添加View视图,其他操作不变,最终的效果就是加了一个边框和上下滚动显示扫描的效果
效果图: