Quartz2D _ 刮刮樂效果

#import "ViewController.h"

@interface ViewController ()

@property(strong, nonatomic) UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 200, 200, 40)];
    label.text = @"刮刮樂, 掛出個帥哥";
    label.backgroundColor = [UIColor orangeColor];
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
    
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 200, 200, 40)];
    self.imageView.image = [UIImage imageNamed:@"1"];
    [self.view addSubview:self.imageView];

    
    
}
//移動手勢
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    //1. 取得一個觸摸對象
    UITouch *touch = touches.anyObject;
    // 取得觸摸對象, 在self.imageView視圖上的位置
    CGPoint point = [touch locationInView:self.imageView];
    
    //2. 設置橡皮擦大小
    CGRect rect = CGRectMake(point.x, point.y, 20, 20);
    
    //3. 開啟圖片上下文
    //參數二: 是否不透明
    UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);
    
    //4. 獲取上下文
    CGContextRef cxt = UIGraphicsGetCurrentContext();
    
    //5. 映射, 將imageView的layer層映射到上下文中
    [self.imageView.layer renderInContext:cxt];
    
    //6. 清除劃過的區域
    CGContextClearRect(cxt, rect);
    
    //7. 獲取圖片的上下文
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    //8. 結束圖片的展示(圖片在上下文中消失)
    UIGraphicsEndImageContext();
    
    
    self.imageView.image = image;
    
    
}

@end```
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容