簡體   English   中英

如何在iOS中使用UIBezierPath繪制直線

[英]how can i draw straight line using UIBezierPath in ios

我正在嘗試在我的視圖上繪制直線....我可以使用該代碼在手指路徑上繪制直線,但是繪制的直線不是直線...似乎像鉛筆一樣拖了線....怎么我能把它弄直嗎..

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

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM