Draw an line in iOS objective C using hand Drawing

Solution:

If you want to draw an line using your hand then use the below code.

Using the touches start and end method to draw the line.

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

UIBezierPath *myPath;
CGPoint firstPoint// (3)
CGPoint initPoint;
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
}


- (voidtouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches]anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
myPath = [UIBezierPath bezierPath];
    firstPoint = touchLocation;
    initPoint = touchLocation;
[myPath moveToPoint:touchLocation];
}

- (voidtouchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UIBezierPath *path = [UIBezierPath bezierPath];
    UITouch *touch = [[event allTouches]anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

[path moveToPoint:CGPointMake(firstPoint.x , firstPoint.y)];
[path addLineToPoint:CGPointMake(touchLocation.x, touchLocation.y)];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor blackColorCGColor];
    shapeLayer.lineWidth = 3.0;
    shapeLayer.fillColor = [[UIColor clearColorCGColor];
    self.view.layer.sublayers = nil;
    [self.view.layer addSublayer:shapeLayer];
    firstPoint = touchLocation;

}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UIBezierPath *path = [UIBezierPath bezierPath];
    UITouch *touch = [[event allTouches]anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    [path moveToPoint:CGPointMake(initPoint.x , initPoint.y)];
    [path addLineToPoint:CGPointMake(touchLocation.x, touchLocation.y)];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = [path CGPath];
        shapeLayer.strokeColor = [[UIColor blackColorCGColor];
        shapeLayer.lineWidth = 3.0;
        shapeLayer.fillColor = [[UIColor clearColorCGColor];
        [self.view.layer addSublayer:shapeLayer];
        firstPoint = touchLocation;
}

@end

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Saved Image in document directory and save path in coredata not able to fetch the image file iOS swift