如何移动 CGPath 而不创建新的
-
20-09-2019 - |
题
我正在创建一个 CGPath
在我的游戏中定义一个区域,如下所示:
CGPathMoveToPoint ( myPath, NULL, center.x, center.y );
CGPathAddLineToPoint( myPath, NULL,center.x + 100, center.y);
CGPathAddLineToPoint( myPath, NULL, center.x + 100, center.y + 100);
CGPathAddLineToPoint( myPath, NULL, center.x, center.y + 100);
CGPathCloseSubpath ( myPath );
我知道这只是一个正方形,我可以使用另一个 CGRect
但我希望实际创建的路径实际上并不是一个矩形(我现在只是在测试)。然后只需使用以下命令即可检测触摸区域:
if (CGPathContainsPoint(myPath, nil, location, YES))
这一切都工作正常,问题是 CGPath
每秒可能移动多达 40 次。我怎样才能移动它而不需要创建一个新的?我知道我可以做这样的事情来“移动”它:
center.y += x;
CGPathRelease(myPath);
myPath = CGPathCreateMutable();
CGPathMoveToPoint ( myPath, NULL, center.x, center.y );
CGPathAddLineToPoint( myPath, NULL,center.x + 100, center.y);
CGPathAddLineToPoint( myPath, NULL, center.x + 100, center.y + 100);
CGPathAddLineToPoint( myPath, NULL, center.x, center.y + 100);
CGPathCloseSubpath ( myPath );
但我必须每秒释放并创建一条最多 40 次的新路径,我认为这可能会降低性能;这是真的?
我希望能够移动它,就像我目前正在移动一些东西一样 CGRects
通过简单地将原点设置为不同的值,这是否可能 CGPath
?
谢谢。
编辑:我忘了提及我没有 GraphicsContext 因为我没有在 UIView
.
解决方案
对 CGPath 应用变换并针对点进行测试,相当于应用 逆 转变到重点。
因此,您可以使用
CGPoint adjusted_point = CGPointMake(location.x - center.x, location.y - center.y);
if (CGPathContainsPoint(myPath, NULL, adjusted_point, YES))
但 CGPathContainsPoint
已经需要一个 CGAffineTransform
参数(你有 NULL
-编辑它),所以你也可以使用
CGAffineTransform transf = CGAffineTransformMakeTranslation(-center.x, -center.y);
if (CGPathContainsPoint(myPath, &transf, location, YES))
如果您正在绘图,则可以直接更改绘图代码中的CTM,而不是更改路径。
CGContextSaveGState(c);
CGContextTranslateCTM(c, center.x, center.y);
// draw your path
CGContextRestoreGState(c);
用一个 CAShapeLayer
如果你需要性能。
其他提示
@KennyTM 的答案非常适合OP的目的,但问题仍然存在:
如何移动 CGPath 而不创建新的?
好吧,两行代码对我来说就成功了:
UIBezierPath* path = [UIBezierPath bezierPathWithCGPath:cgPath];
[path applyTransform:CGAffineTransformMakeTranslation(2.f, 0.f)];
不隶属于 StackOverflow