橡皮擦


- (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<UITouch *> *)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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值