iOS 图片擦除

2016-01-22  本文已影响705人  smirkk
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    
    [self.view addGestureRecognizer:pan];
}

#define clipWH 30
- (void)pan:(UIPanGestureRecognizer *)pan
{
    // 获取当前触摸点
    CGPoint curP = [pan locationInView:self.view];
    
    // 获取擦除的矩形范围
    CGFloat wh = clipWH;
    CGFloat x = curP.x - wh * 0.5;
    CGFloat y = curP.y - wh * 0.5;
    CGRect rect = CGRectMake(x, y, wh, wh);
    
    // 开启位图上下文
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
    // 获取当前上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext(
    
    // 渲染控件
    [self.imageView.layer renderInContext:ctx];
    // 擦除上下文的某一部分
    CGContextClearRect(ctx, rect);
    // 生成一张图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    self.imageView.image = image;
    // 关闭上下文
    UIGraphicsEndImageContext(); 
}
上一篇下一篇

猜你喜欢

热点阅读