是否可以在Sprite Kit中使用圆圈(SKShapeNode)作为遮罩? [英] Is it possible to use a circle (SKShapeNode) as a mask in Sprite Kit?
问题描述
我正在尝试在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中进行实验,我有一个非常糟糕的修复方法。
After much swearing, scouring the web, and experimentation in Xcode, I have a really hacky fix.
请记住,这是一个非常讨厌的黑客 - 但你可以责怪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
兄弟节点无法屏蔽(例如SKLabelNode
s)
- 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.SKLabelNode
s)
不是理想的事态。
灵感来自 Tony Chamblee的进度计时器,'fix'是完全免除填充,只需使用路径的笔划:
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.
希望Apple将来会考虑这个问题。现在,这个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)作为遮罩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!