這兩天閑來無事,做一個“刮刮樂”的小功能給大家樂一樂。哈哈哈,先來看看效果圖:
刮刮樂.gif
這個女朋友獎很簡單就可以實現:
1.創建圖片上下文。
2.將圖片渲染在上下文中。
3.清除手指拖拽的位置。
4.通過上下文生成新的圖片。
5.將新的圖片添加在UIImageView上,并且關閉上下文。
理論上就這么點東西哈。
#import "ViewController.h"
@interface ViewController ()
// 灰色(將被刮開的圖片)
@property (weak, nonatomic) IBOutlet UIImageView *clearImageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 添加Pan手勢
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
[self.clearImageView addGestureRecognizer:pan];
}
#pragma mark - 長按事件
-(void)panAction:(UIPanGestureRecognizer *)pan {
// 獲取當前按的點
CGPoint curPoint = [pan locationInView:self.clearImageView];
// 創建圖片上下文
UIGraphicsBeginImageContext(self.clearImageView.bounds.size);
// 獲取對應的上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 將圖片渲染在t上下文中
[self.clearImageView.layer renderInContext:context];
// 清除手指選中的地方
CGContextClearRect(context, CGRectMake(curPoint.x - 15, curPoint.y - 15, 30, 30));
// 通過上下文合成圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 結束上下文
UIGraphicsEndImageContext();
// 將新的圖片添加在視圖上
self.clearImageView.image = image;
}
@end
是不是很簡單,這些小功能其實很有意思,喜歡的朋友可以點個贊哈。