有没有可能在 SpriteKit 中创建渐变填充框的方法?我尝试用它填充形状节点,但它指出只有纯色适用于 skshapenode。
4 回答
我认为 current 不可能做到这一点SKShapeNode
,它目前几乎没有处理其基本功能。如果您不想使用预先存在的精灵渐变图像,一个好方法是创建一个SKTexture
from 将 a CIFilter
(可能CILinearGradient
在这种情况下)应用到基本盒子图像,然后创建SKSpriteNode
from that SKTexture
。
这是一个解决方案。(注意,我正在使用 Rubymotion,一个用于 Objective C / iOS 的 ruby 绑定,但是逻辑是完全相同的。如果有人想编辑它并放置目标 c 等价物,请继续
size = CGSizeMake(50,50)
scale = options[:scale] || UIScreen.mainScreen.scale
opaque = options.fetch(:opaque, false)
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
context = UIGraphicsGetCurrentContext()
gradient = CAGradientLayer.layer
gradient.frame = CGRectMake(0,0,50,50)
gradient.colors = [SKColor.blackColor.CGColor,SKColor.whiteColor.CGColor]
gradient.renderInContext(context)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
texture = SKTexture.textureWithCGImage(image.CGImage)
node = SKSpriteNode.alloc.initWithTexture(texture)
好的,这是我现在正在使用的东西。我基于 AwDogsGo2Heaven 的解决方案,但适用于 Mac。使用一种完全兼容的解决方案会很甜蜜。我不确定如何创建上下文。但似乎有效。我也不确定规模。在视网膜 mac 和非视网膜 mac 上运行,看不到任何问题,但上下文是使用 scale 2 创建的,因此对于非视网膜 mac 来说可能是过度杀伤力。我把它放在 SKTexture 的一个类别中。
为了使用它,只需调用+(SKTexture*)gradientWithSize:(const CGSize)SIZE colors:(NSArray*)colors
.
编辑:更新代码和更多讨论:渐变纹理在视网膜 Mac 上的比例错误
马特的回答是正确的,但我还无法添加渐变。这是我目前的尝试,如果有人知道如何使它工作,请更新线程。
这是核心图像参考
CIFilter *gradientFilter = [CIFilter filterWithName:@"CILinearGradient"];
//[gradientFilter setDefaults];
CIColor *startColor = [CIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
CIColor *endColor = [CIColor colorWithRed:0 green:0 blue:0 alpha:1.0];
CIVector *startVector = [CIVector vectorWithX:0 Y:0];
CIVector *endVector = [CIVector vectorWithX:0.21 Y:0.31];
[gradientFilter setValue:startVector forKey:@"inputPoint0"];
[gradientFilter setValue:endVector forKey:@"inputPoint1"];
[gradientFilter setValue:startColor forKey:@"inputColor0"];
[gradientFilter setValue:endColor forKey:@"inputColor1"];
SKEffectNode *effectNode = [SKEffectNode node];
effectNode.filter = gradientFilter;
effectNode.shouldEnableEffects = YES;
[self addChild:effectNode];
//effectNode.position = CGPointMake(200, 200);
另一个测试过滤器的好方法是从 WWDC 2013下载演示应用程序CIFunHouse 。