如何在ios中使用UIBezierPath绘制直线

时间:2015-03-10 10:43:58

标签: ios xcode drawing

我试图在我的视线上绘制直线....我可以在我的手指路径上用该代码绘制线条,但绘制的线条并不是直线的......看起来像是用铅笔钻了...那我怎么能直接做好..

@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];
}

1 个答案:

答案 0 :(得分:1)

试试这个:

@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];
}