我正在使用SKShapeNodes通过在用户触摸屏幕时更新路径属性来动态绘制线条。一旦线完成,我想在路径的末尾添加一条新的固定长度垂直线。
我已经调查了CGAffineTransform以根据路径的终点旋转新行,但到目前为止还没有任何运气。任何提示或见解都将非常感激。
我目前的一些参考代码如下:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
//add a line to the new coordinates the user moved to
CGPathAddLineToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//create local copy of path
CGPathRef myPath_ = pathToDraw;
CGPoint myPoint = CGPathGetCurrentPoint(pathToDraw);
//create rectangle to append to end of line
CGRect newRect = CGRectMake(myPoint.x, myPoint.y, 25, 3);
CGPathRef newPath = CGPathCreateWithRect(newRect, NULL);
//add new line to the end of the path
CGPathAddPath(newPath, NULL, myPath_);
//set shape node path to drawn path
lineNode.path = myPath_;
}
答案 0 :(得分:3)
要获得垂线,您可以将矢量指向最后一个线段的方向,然后交换x和y,并反转其中一个。像这样:
CGPoint v = { currentPoint.x - lastPoint.x, currentPoint.y - lastPoint.y };
CGPoint perp;
if (v.x == 0)
{
perp.x = -v.y;
perp.y = v.x;
}
else
{
perp.x = v.y;
perp.y = -v.x;
}
现在你可以在perp
方向画一条线,从当前点开始,就像这样:
CGPathMoveToPoint (somePath, currentPoint);
CGPathAddLineToPoint (somePath, NULL, currentPoint.x + perp.x * length, currentPoint.y + perp.y * length);
其中length
是您要绘制的线段的长度。
并且不要忘记将lastPoint
设置为currentPoint
,以便下次更正:
lastPoint = currentPoint;