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

标签 ios xcode drawing

我正在尝试在我的 View 上画直线......我可以用那个代码在我的手指路径上画线但是画的线不是直的......它看起来像是用铅笔画的...... .所以我怎样才能让它变直..

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

关于ios - 我如何在 ios 中使用 UIBezierPath 绘制直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28961623/

相关文章:

c# - 如何使用 C# 渲染 pdf

ios - 在 segue 之前检查条件

ios - 将 CSS 框阴影转换为 iOS 阴影

ios - PresentViewController(UIViewController) 不工作

ios - UITableView 背景上的 UIGestureRecognizer

ios - 在 Swift 中使用 MKLocalSearch 将一个图钉附加到用户位置,而不是蓝点

ios - 某些角度的连接线具有尖的顶点而不是圆形的

android - 如何在 View 上模拟橡皮擦?

xcode - Xcode 测试导航器中保留已删除的测试

React Native 项目的 xcode 存档 "Library not found for -lReact-hermes"