Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Clear view or image with touch in iOS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 302
    Comment on it

    Hi Readers,

    Paint related apps are usually used to clear content what have been drawn. One can achieve it by using Core Graphics framework provided by iOS.

    With touch delegate methods will be called so following code snippet will give proper idea about code:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        lastTouch = [touch locationInView:frontImage];
    }
    
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        currentTouch = [touch locationInView:frontImage];
        
    
        CGFloat brushSize = yourCircleRadius;
        CGColorRef strokeColor = [UIColor whiteColor].CGColor;
        
        UIGraphicsBeginImageContext(frontImage.frame.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [frontImage.image drawInRect:CGRectMake(0, 0, frontImage.frame.size.width, frontImage.frame.size.height)];
        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextSetLineWidth(context, brushSize);
        CGContextSetStrokeColorWithColor(context, strokeColor);
        CGContextSetBlendMode(context, kCGBlendModeClear);
        CGContextBeginPath(context);
        CGContextMoveToPoint(context, lastTouch.x, lastTouch.y);
        CGContextAddLineToPoint(context, currentTouch.x, currentTouch.y);
        CGContextStrokePath(context);
        frontImage.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        lastTouch = [touch locationInView:frontImage];
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        
    }

    Where frontImage is image view on which clear operation will perform.  As you can see here we are defining delegate methods with CGContext. And we are drawing Rect for frontImage image and clear content over it. With current context, we are clearing content with CGContextSetBlendMode method.

    Clearing content will be performed with the help of line path which we draw to clear. lastTouch is used to get the point at starting the touch and currentTouch are points which got by moving touch.

    Hope it helps.

    Thanks for reading.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: