Drawing on a UIView through gestures

Drawing on a UIView through gestures

Screenshot 2015-06-27 09.27.50

 

My latest project on GitHub shows how to draw on the canvas with interaction from different touch gestures.  The project can be found here:  https://github.com/BeanoKing/UIBezierPath-Rotation

All that needs to be done on the view in order to interact with gestures is to add the UIGestureRecognizerDelegate to your header file.

#import <UIKit/UIKit.h>

@interface CustomView : UIView <UIGestureRecognizerDelegate>

@end

Now in your implementation you have access to these events:

- (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event
{
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    
    [self setNeedsDisplay];
}

- (void) touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    
    [self setNeedsDisplay];
}

- (void) touchesEnded:(NSSet *) touches withEvent:(UIEvent *) event
{
    [self setNeedsDisplay];
}

Notice in the began and moved I’m capturing the point on the screen. I’ve left out the implementation of what to do with those points, which you can get from the project on GitHub.

A key when doing custom drawing is call [self setNeedsDisplay] whenever you want to re-draw the UI.  This will call the drawRect method where all of you drawing code needs to go.  The entire UI will be redrawn when this is called, so anything you want to stay on the UI needs to be here.

- (void)drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext ();
    CGContextSaveGState (context);
    
    const CGFloat *components = CGColorGetComponents([UIColor blueColor].CGColor);
    [[UIColor colorWithRed:components[0] green:components[1] blue:components[2] alpha:0.7] setFill];
    
    [[UIColor blueColor] setStroke];
    
    rectangle = CGRectMake(200,300,300,300);
    
    rectPath = [UIBezierPath bezierPathWithRect:rectangle];
    
    [rectPath setLineWidth:2.0f];
    [rectPath stroke];
    
    [rectPath fill];
    
    CGContextRestoreGState (context);
}

This code is drawing a big blue rectangle with dimensions of 300×300 with a lighter blue fill and a blue outline. It’s also being placed at the 200 x coordinate and the 300 y coordinate. 0 is the upper left corner on the UIView canvas.

A lot of the implementation and logic can be found in the GitHub project. This was just a high level overview of how to draw on a UIView and capture gestures. If you have any questions on the project leave a comment and I’ll get back to you.

Comments are closed.