图片擦除效果实例

ViewController.m

#import "ViewController.h"
#import "EraseView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //先放置一个背景图片
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = [UIScreen mainScreen].bounds;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.image = [UIImage imageNamed:@"psb1"];
    [self.view addSubview:imageView];

    //在放置一个可以擦除的前景View,擦除后显出背景图片
    EraseView *eraseView = [[EraseView alloc] init];
    eraseView.frame = [UIScreen mainScreen].bounds;
    [self.view addSubview:eraseView];
}

@end

EraseView.m

#import "EraseView.h"

#define ERASE_SIZE 50

@interface EraseView()

@property(nonatomic,strong)UIImageView *imageView;

@property(nonatomic,assign)CGPoint currentPoint;

@property(nonatomic,assign)BOOL isTouched;

@end

@implementation EraseView

- (instancetype)init
{
    if(self = [super init])
    {
        self.backgroundColor = [UIColor clearColor];

        self.imageView = [[UIImageView alloc]init];
        self.imageView.image = [UIImage imageNamed:@"psb"];
        self.imageView.contentMode = UIViewContentModeScaleAspectFill;

        [self addSubview:self.imageView];

        [self.imageView setUserInteractionEnabled:YES];

        [self addPan];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    self.imageView.frame = [UIScreen mainScreen].bounds;
}

- (void)drawRect:(CGRect)rect {

    UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0);

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    [self.imageView.image drawInRect:self.imageView.frame];

    if(self.isTouched)
    {
        CGContextClearRect(ctx, CGRectMake(self.currentPoint.x - ERASE_SIZE * 0.5, self.currentPoint.y - ERASE_SIZE * 0.5, ERASE_SIZE, ERASE_SIZE));
    }

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    self.imageView.image = newImage;
}

- (void)addPan
{
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(onPan:)];
    [self.imageView addGestureRecognizer:pan];
}

- (void)onPan:(UIPanGestureRecognizer*)pan
{
    self.currentPoint = [pan locationInView:self.imageView];
    if(pan.state == UIGestureRecognizerStateBegan)
    {
        self.isTouched = YES;
    }
    else if(pan.state == UIGestureRecognizerStateChanged)
    {
        NSLog(@"%f,%f",self.currentPoint.x,self.currentPoint.y);
        [self setNeedsDisplay];
    }
    else if(pan.state == UIGestureRecognizerStateEnded)
    {
        self.isTouched = NO;
    }
}

@end

results matching ""

    No results matching ""