Ketan Jogal
Ketan Jogal

Reputation: 58

how can i draw straight line using UIBezierPath in ios

i am trying to draw straight line on my view....i can draw line on my finger path with that code but the line that drawn that is not straight ...it seems like it drwan with pencil....so how can i make it straight..

@implementation View

{
UIBezierPath *path; // (3)
}

- (id)initWithCoder:(NSCoder *)aDecoder // (1)
{
if (self = [super initWithCoder:aDecoder])
{
    [self setMultipleTouchEnabled:NO]; // (2)
    [self setBackgroundColor:[UIColor whiteColor]];
    path = [UIBezierPath bezierPath];
    [path setLineWidth:5.0];
}
return self;
}

- (void)drawRect:(CGRect)rect // (5)
{
[[UIColor blackColor] setStroke];
[path stroke];
}


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

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

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

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

Upvotes: 1

Views: 1981

Answers (1)

Fabio Felici
Fabio Felici

Reputation: 2916

Try this:

@implementation View

{
NSMutableArray paths;
UIBezierPath *currentPath;
CGPoint startPoint;
}

- (id)initWithCoder:(NSCoder *)aDecoder // (1)
{
if (self = [super initWithCoder:aDecoder])
{
    [self setMultipleTouchEnabled:NO]; // (2)
    [self setBackgroundColor:[UIColor whiteColor]];
    paths = [NSMutableArray array];
}
return self;
}

- (void)drawRect:(CGRect)rect // (5)
{
[[UIColor blackColor] setStroke];
for(UIBezierPath *path in paths) {
    [path stroke];
}
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
startPoint = [touch locationInView:self];
currentPath = [UIBezierPath bezierPath];
[currentPath setLineWidth:5.0];
[paths addObject:currentPath];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:self];
[currentPath removeAllPoints];
[currentPath moveToPoint:startPoint];
[currentPath addLineToPoint:p]; // (4)
[self setNeedsDisplay];
}

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

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

Upvotes: 1

Related Questions