iOS 指定区域透明 刮刮卡效果

使视图的部分区域透明,我们可以使用CGContext来实现:

    // 默认是去创建一个透明的视图

    UIGraphicsBeginImageContextWithOptions(view, NO, 0);

    // 获取上下文(画板)

    CGContextRef ref = UIGraphicsGetCurrentContext();

    // 把view的layer映射到上下文中

    [view.layer renderInContext:ref];

    // 设置画板的绘制样式,kCGBlendModeClear为清除

    CGContextSetBlendMode(ref, kCGBlendModeClear);

//方案1

    // 设置清除区域为一个圆形,假设中心点为cententPoint

        CGContextAddArc(ref, cententPoint.x, cententPoint.y, width/2.0,0,M_PI*2,1);

        CGContextFillPath(ref);

//方案2

    // 设置清除区域为划过的线条,假设当前触摸点为cententPoint,纪录上一个触摸点为lastPoint

        CGContextBeginPath(ref);

        CGContextMoveToPoint(ref, lastPoint.x, lastPoint.y);

        CGContextAddLineToPoint(ref, centerPoint.x, centerPoint.y);

    //将当前触摸点cententPoint赋值给lastPoint,以便下一个触摸点调用

        lastPoint = cententPoint;

//设置画笔颜色为透明

    CGContextSetStrokeColorWithColor(ref, [[UIColor clearColor] CGColor]);

    CGContextStrokePath(ref);

// 获取部分区域透明的图片

   UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

// 结束图片的画板

   UIGraphicsEndImageContext(); 

//接下来我们可以将这个图片绘制到view上,最简便的可以使用UIImageView来实现

//实现刮卡效果,我们可以在[UIViewController touchesMoved: withEvent:]中获取触摸点,通过上述方法来实现

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

    // 触摸任意位置

    UITouch*touch = touches.anyObject;

    // 触摸位置在图片上的坐标

    CGPoint cententPoint = [touch locationInView:self.imageV];

    // 设置清除点的大小

    CGFloat width =20;

    //执行上述操作

    //    self.imageV.image = image;

}

//如果选择方案2实现,还需要在[UIViewController touchesBegan: withEvent:]中初始化第一个触摸点

- (void)touchesBegan:(NSSet *)toucheswithEvent:(UIEvent*)event { 

    //初始化第一个触摸点

    lastPoint = [[touches anyObject]locationInView:self];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。