支付寶里有個刮刮樂中獎, 和大街小巷里的類似彩票刮刮樂的效果一樣译蒂。
刮刮樂
實(shí)現(xiàn)思路, 其實(shí)很簡單的三步:
- 展示刮出來的效果的view: 即刮開后刮刮樂效果展示-顯示的文字Label
- 設(shè)置遮擋在外面的Image(被刮的圖片)
- 在touchesMoved方法里面實(shí)現(xiàn)操作: 刮開圖片獲取文字
雖然思路簡單,但是還需要注意:
- 這兩個控件的位置切記要相同!
- 一定要先創(chuàng)建下面的展示刮出來的效果控件的, 再創(chuàng)建上面的被刮的圖片控件!
下面就直接上代碼!
- (void)setupSubViews {
// 1.展示刮開出來的效果:顯示的文字 label
UILabel *showLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 274, 145)];
showLabel.center = self.view.center;
showLabel.backgroundColor = [UIColor redColor];
showLabel.textColor = [UIColor yellowColor];
showLabel.text = @"恭喜你中獎了";
showLabel.font = [UIFont systemFontOfSize:30];
showLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:showLabel];
// 2.設(shè)置遮擋在外面的Image(被刮的圖片)
UIImageView *scratchedImg = [[UIImageView alloc] initWithFrame:showLabel.frame];
scratchedImg.image = [UIImage imageNamed:@"scratched"];
[self.view addSubview:scratchedImg];
self.scratchedImg = scratchedImg;
}
// 3.在touchesMoved方法里面實(shí)現(xiàn)操作
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 觸摸任意位置
UITouch *touch = touches.anyObject;
// 觸摸位置在圖片上的坐標(biāo)
CGPoint cententPoint = [touch locationInView:self.scratchedImg];
// 設(shè)置清除點(diǎn)的大小
CGRect rect = CGRectMake(cententPoint.x, cententPoint.y, 20, 20);
// 默認(rèn)是去創(chuàng)建一個透明的視圖
UIGraphicsBeginImageContextWithOptions(self.scratchedImg.bounds.size, NO, 0);
// 獲取上下文(畫板)
CGContextRef ref = UIGraphicsGetCurrentContext();
// 把imageView的layer映射到上下文中
[self.scratchedImg.layer renderInContext:ref];
// 清除劃過的區(qū)域
CGContextClearRect(ref, rect);
// 獲取圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 結(jié)束圖片的畫板, (意味著圖片在上下文中消失)
UIGraphicsEndImageContext();
self.scratchedImg.image = image;
}
貼上 Demo , 如果需要直接這里下載就可以嘍~