橡皮擦

作者: 路灯下的黑猫 | 来源:发表于2018-08-24 14:34 被阅读0次

    - (void)viewDidLoad {

        [super viewDidLoad];

        //初始化要显示在下面的提示label

        UILabel*label = [[UILabelalloc]initWithFrame:CGRectMake(100,100,200,50)];

        label.textAlignment = NSTextAlignmentCenter;

        label.text=@"刮开看看你中奖啦!";

        [self.viewaddSubview:label];

        //初始化显示在上面的imageview(用上面的根据颜色生成图片方法生成一个灰色的图层,看起来像一种刮奖的图层)

        self.imageView= [[UIImageViewalloc]init];

        self.imageView.image= [selfimageWithColor:[UIColorgrayColor]];

        self.imageView.frame=CGRectMake(100,100,200,50);

        [self.viewaddSubview:self.imageView];

    }

    //刮奖()

    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent*)event

    {

        UITouch*touch = touches.anyObject;

        CGPointpoint = [touchlocationInView:self.imageView];

        //滑块区域(触碰到的点放大成正方形)

        CGRectrect =  CGRectMake( point.x-10,point.y-10,20,20);

        //获取上下文(这里记得一定要透明)

        UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);

        CGContextRefref =  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 {

        CGRectrect =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();

        returnimage;

    }

    相关文章

      网友评论

        本文标题:橡皮擦

        本文链接:https://www.haomeiwen.com/subject/vswbiftx.html