本次讲的手势密码,是在九个按键上实现的,这里讲的是手势密码的基本实现和效果
同样先上效果图

其实就是对画图功能的一个实现,再加上手势操作结合起来。
屏幕宽度高度,方便下面操作,不做解释
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width
控制器.m文件
这里的imageView是用来装手势画图之后的image,看后面就清楚了
@property (nonatomic,strong)NSMutableArray *buttonArr;//全部手势按键的数组
@property (nonatomic,strong)NSMutableArray *selectorArr;//选中手势按键的数组
@property (nonatomic,assign)CGPoint startPoint;//记录开始选中的按键坐标
@property (nonatomic,assign)CGPoint endPoint;//记录结束时的手势坐标
@property (nonatomic,strong)UIImageView *imageView;//画图所需
-(NSMutableArray *)selectorArr
{
if (!_selectorArr) {
_selectorArr = [[NSMutableArray alloc]init];
}
return _selectorArr;
}
添加九个按键,设置状态图片,实际开发中一般有三种状态,即默认,选中正确和选择错误,错误一般指的是我们要记录下用户的手势密码,需要用户。
画出两次相同的手势密码才能保存,若两次输入不一致,就是错误状态的一种,当然还包括其它的,不多说了。
这里要强调
btn.userInteractionEnabled = NO;
这句的重要性,如果不关闭按键的用户交互,下面的UITouch则无法在按键中触发,所以这里必须关闭
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
if (!_buttonArr) {
_buttonArr = [[NSMutableArray alloc]initWithCapacity:9];
}
self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
[self.view addSubview:self.imageView];
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(ScreenWidth/12+ScreenWidth/3*j, ScreenHeight/3+ScreenWidth/3*i, ScreenWidth/6, ScreenWidth/6);
[btn setImage:[UIImage imageNamed:@"pbg"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"pbg01"] forState:UIControlStateHighlighted];
btn.userInteractionEnabled = NO;
[self.buttonArr addObject:btn];
[self.imageView addSubview:btn];
}
}
}
这个方法就是实现画图的方法
-(UIImage *)drawLine{
UIImage *image = nil;
UIColor *col = [UIColor colorWithRed:1 green:0 blue:0 alpha:1];
UIGraphicsBeginImageContext(self.imageView.frame.size);//设置画图的大小为imageview的大小
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5);
CGContextSetStrokeColorWithColor(context, col.CGColor);
CGContextMoveToPoint(context, self.startPoint.x, self.startPoint.y);//设置画线起点
//从起点画线到选中的按键中心,并切换画线的起点
for (UIButton *btn in self.selectorArr) {
CGPoint btnPo = btn.center;
CGContextAddLineToPoint(context, btnPo.x, btnPo.y);
CGContextMoveToPoint(context, btnPo.x, btnPo.y);
}
//画移动中的最后一条线
CGContextAddLineToPoint(context, self.endPoint.x, self.endPoint.y);
CGContextStrokePath(context);
image = UIGraphicsGetImageFromCurrentImageContext();//画图输出
UIGraphicsEndImageContext();//结束画线
return image;
}










