本文介绍了是否可以在 Sprite Kit 中使用圆形(SKShapeNode)作为蒙版?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Sprite Kit 项目中创建一个圆形蒙版.我像这样创建圆圈(将其定位在屏幕的中心):

I'm trying to create a circular mask in a Sprite Kit project. I create the circle like this (positioning it at the centre of the screen):

SKCropNode *cropNode = [[SKCropNode alloc] init];

SKShapeNode *circleMask = [[SKShapeNode alloc ]init];
CGMutablePathRef circle = CGPathCreateMutable();
CGPathAddArc(circle, NULL, CGRectGetMidX(self.frame), CGRectGetMidY(self.frame), 50, 0, M_PI*2, YES);
circleMask.path = circle;
circleMask.lineWidth = 0;
circleMask.fillColor = [SKColor blueColor];
circleMask.name=@"circleMask";

在代码的下方,我将其设置为 cropNode 的掩码:

and further down the code, I set it as the mask for the cropNode:

[cropNode setMaskNode:circleMask];

...但内容不是显示在圆圈内,而是显示为正方形.

... but instead of the content showing inside a circle, the mask appears as a square.

是否可以使用 SKShapeNode 作为遮罩,还是需要使用图像?

Is it possible to use a SKShapeNode as a mask, or do I need to use an image?

推荐答案

经过大量的咒骂、搜索网络和在 Xcode 中的实验,我有一个非常hacky 的解决方案.

After much swearing, scouring the web, and experimentation in Xcode, I have a really hacky fix.

请记住,这是一个非常讨厌的 hack - 但您可以将其归咎于 Sprite Kit 的 SKShapeNode 实现.向路径添加填充会导致以下情况:

Keep in mind that this is a really nasty hack - but you can blame that on Sprite Kit's implementation of SKShapeNode. Adding a fill to a path causes the following:

  • 为您的场景添加一个额外的节点
  • 路径变得不可屏蔽 - 它出现在掩码之上"
  • 使任何非SKSpriteNode 兄弟节点不可屏蔽(例如SKLabelNodes)
  • adds an extra node to your scene
  • the path becomes unmaskable - it appears 'over' the mask
  • makes any non-SKSpriteNode sibling nodes unmaskable (e.g. SKLabelNodes)

不是一个理想的状态.

灵感来自 Tony Chamblee 的进度计时器,'修复'是完全省去填充,只使用路径的笔划:

Inspired by Tony Chamblee's progress timer, the 'fix' is to dispense with the fill altogether, and just use the stroke of the path:

SKCropNode *cropNode = [[SKCropNode alloc] init];

SKShapeNode *circleMask = [[SKShapeNode alloc ]init];
CGMutablePathRef circle = CGPathCreateMutable();
CGPathAddArc(circle, NULL, CGRectGetMidX(self.frame), CGRectGetMidY(self.frame), 50, 0, M_PI*2, YES); // replace 50 with HALF the desired radius of the circle
circleMask.path = circle;
circleMask.lineWidth = 100; // replace 100 with DOUBLE the desired radius of the circle
circleMask.strokeColor = [SKColor whiteColor];
circleMask.name=@"circleMask";

[cropNode setMaskNode:circleMask];

如上所述,您需要将半径设置为通常的一半,并将线宽设置为半径的两倍.

As commented, you need to set the radius to half of what you'd normally have, and the line width to double the radius.

希望苹果将来会关注这一点;目前,这个 hack 是我找到的最好的解决方案(除了使用图像,如果你的蒙版需要是动态的,这真的不起作用).

Hopefully Apple will look at this in future; for now, this hack is the best solution I've found (other than using an image, which doesn't really work if your mask needs to be dynamic).

这篇关于是否可以在 Sprite Kit 中使用圆形(SKShapeNode)作为蒙版?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:38