橡皮擦


- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化要显示在下面的提示label
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"恭喜您中奖了";
    [self.view addSubview:label];
    //初始化显示在上面的imageview(用上面的根据颜色生成图片方法生成一个灰色的图层,看起来像一种刮奖的图层)
    self.imageView = [[UIImageView alloc] init];
    self.imageView.image = [self imageWithColor:[UIColor grayColor]];
    self.imageView.frame = CGRectMake(100, 100, 200, 50);
    [self.view addSubview:self.imageView];




}






//刮奖()
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self.imageView];
    //滑块区域(触碰到的点放大成正方形)
    CGRect rect =  CGRectMake( point.x - 10,point.y - 10, 20, 20);
    //获取上下文(这里记得一定要透明)
    UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);
    CGContextRef ref =  UIGraphicsGetCurrentContext();
    //把imageView的layer映射到上下文中(这个是核心,由于UIView本质上显示东西的layer层,所以实质是将imageView显示的东西全部复制给上下文,app中长用到的截屏就利用了这个原理)
    [self.imageView.layer renderInContext:ref];
    //清除划过的区域
    CGContextClearRect(ref, rect);
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //返回图片并不断的传给UIImageView上去显示
    self.imageView.image = image;

}

- (UIImage *)imageWithColor:(UIColor *)color {

    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

你可能感兴趣的:(Quartz2D)