ios - 使用 SKShapeNode 和 CGPath 在 Sprite Kit 中绘制虚线

标签 ios sprite-kit uibezierpath cgpath skshapenode

我想在我的 sprite kit 游戏中画一条虚线,我可以使用 SKShapeNode 节点画一条法线,如下所示:

 UIBezierPath *_path=[UIBezierPath bezierPath];
 //1
 CGPoint point1 = CGPointMake(100,100);
 CGPoint point2 = CGPointMake(150,150);
 [_path moveToPoint:point1];
 [_path addLineToPoint:point2];
 //2
 SKShapeNode *line = [SKShapeNode node];
 line.path = _path.CGPath;

我尝试像这样为 UIBezierPath 设置虚线模式:

// adding this code at location 1 or 2 above but no effect
CGFloat dashes[] = {6, 2};
[_path setLineDash:dashes count:2 phase:0];

但未应用虚线图案。

我还尝试直接从 UIBezierpath.CGPath 属性创建 CGPath 的虚线副本:

 CGFloat dashes[] = {6, 2};
 CGPathRef aCGPath= CGPathCreateCopyByDashingPath(_path.CGPath,NULL,0,dashes,2);
line.path = aCGPath;

也一样。

如果有人能解释问题所在以及如何通过将虚线 cgpath 应用于 skshapenode 在两点之间绘制虚线,我将非常感激。

编辑:我知道对于这个简单的例子,我可以将这两个点之间的距离划分为小的固定距离,并通过 bezeirpath 移动和绘制虚线,但考虑一个自由手路径,点来自触摸,这是一个非常复杂且用固定长度的点重新绘制路径然后绘制破折号是低效的。我想知道是否有办法将虚线图案应用于路径并让 skshapenode 使用它,这是我的问题。

最佳答案

如果有人仍然对这个问题的简单答案感兴趣:

使用 CGPathCreateCopyByDashingPath 创建 dashed 副本 - [UIBezierCurve CGPath]

CGPathRef CGPathCreateCopyByDashingPath(
   CGPathRef path,
   const CGAffineTransform *transform,
   CGFloat phase,
   const CGFloat *lengths,
   size_t count
);

并将其添加到 SKShapeNodepath 属性中。

例子:

    // creates a dashed pattern
    CGFloat pattern[2];
    pattern[0] = 10.0;
    pattern[1] = 10.0;
    CGPathRef dashed =
    CGPathCreateCopyByDashingPath([bezierPath CGPath],
                                  NULL,
                                  0,
                                  pattern,
                                  2);

    self.myShapeNode.path = dashed;

    CGPathRelease(dashed);

编辑:为了提高性能,您可以将 SKShapeNode 添加到 SKEffectNode 并将 shouldRasterize 属性设置为 YES.

关于ios - 使用 SKShapeNode 和 CGPath 在 Sprite Kit 中绘制虚线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20778681/

相关文章:

ios - SKSpriteNode 减慢但不应该

ios - 贪吃蛇游戏运动问题 Spritekit

ios - 如何在 SKView 之上添加 SCNView

ios - 使用 UIBezierPath 异步剪辑 UIImage

ios - 如何在iOS中绘制类似图形的平行四边形?

ios - UITabBarControllerDelegate - 不为委托(delegate)触发的方法?

ios - get "Undefined symbols for architecture i386:"尝试获取常量

ios - 无法快速引用 Xcode GameScene.sks

ios - 创建带圆角的 View (四分之一圆)

ios - 当物理体没有 collisionBitMask 时,usePreciseCollisionDetection 属性是否起作用