我尝试根据用户触摸在两个点之间添加线(起点将是用户的第一个触摸和终点将是用户在视图上的第二次触摸).I能够使用下面的代码绘制它。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 2)
{
NSLog(@"touch count 2");
return;
}
if(isOdd)//View already has user's start point
{
nextPoint = [touch locationInView:self.view];
point2 = nextPoint;
//nextPoint.y -= 20;
[self drawLineFromPoint:currentPoint toPoint:nextPoint];
currentPoint = nextPoint;
NSLog(@"x:%f,y:%f",currentPoint.x,currentPoint.y);
isOdd = YES;
}
else
{
currentPoint = [touch locationInView:self.view];
point1 = currentPoint;
NSLog(@"x:%f,y:%f",currentPoint.x,currentPoint.y);
isOdd = YES;
}
}
-(void)drawLineFromPoint:(CGPoint)start toPoint:(CGPoint)end
{
UIBezierPath *path = [UIBezierPath new];
[path moveToPoint:start];
[path addLineToPoint:end];
CAShapeLayer *shapeLayer = [CAShapeLayer new];
shapeLayer.path = path.CGPath;
shapeLayer.strokeColor = [UIColor greenColor].CGColor;
shapeLayer.lineWidth = 3.0;
[self.myView.layer addSublayer:shapeLayer];
}
现在我的问题是,当用户尝试使用手指拖动/移动该线时,是否可以弯曲该线?
答案 0 :(得分:1)
如果您的问题是绘制已经绘制的线条,那么您可以尝试以下方法:
如您所知,该线的起点和终点,您可以在手指移动时重绘曲线
current => head_ref
prev => NULL;
current => head_ref;
next => null;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
UIBezierPath的功能,其中控制点将是移动期间的当前触摸点。 在使用
调用此函数之前,您必须移动到起点- addQuadCurveToPoint:controlPoint:
并将终点作为上述曲线函数的目标点。
答案 1 :(得分:0)
使用CAShapeLayer在A点(startingPoint)和B点(endingPoint)之间画一条直线。
@interface ViewController()
{
CGFloat startingPoint,endingPoint;
}
@end
@implementation ViewController()
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
//Take the first point A from touch began
startingPoint = [touch locationInView:baseHolderView];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
endingPoint = [touch locationInView:baseHolderView];
//Take the Second point b from touch Ended
[self makeLineLayer:baseHolderView.layer lineFromPointA:startingPoint toPointB:endingPoint];
}
-(void)makeLineLayer:(CALayer *)layer lineFromPointA:(CGPoint)pointA toPointB:(CGPoint)pointB
{
CAShapeLayer *line = [CAShapeLayer layer];
UIBezierPath *linePath=[UIBezierPath bezierPath];
[linePath moveToPoint: pointA];
[linePath addLineToPoint:pointB];
line.path=linePath.CGPath;
line.fillColor = nil;
line.opacity = 2.0;
line.strokeColor = [UIColor blackColor].CGColor;
[layer addSublayer:line];
}
@end