2013-10-08 37 views
8

是否有任何可能的方式在SpriteKit中創建漸變填充框?我試過用這個填充一個形狀節點,但是它注意到只有純色可以用於skshapenode。如何在Spritekit中創建漸變?

+0

我回來了..並發現這一點:https://gist.github.com/Tantas/7fc01803d6b559da48d6 – Jonny

+0

參見本https://開頭計算器/我的問題/ 18894493/making-a-skscenes-background-transparent-not-working-is-this-a-bug/24494346#24494346 – Suresh

回答

4

目前SKShapeNode我不認爲這是可能的,目前勉強處理其基本功能。如果不想使用預先存在的精靈漸變圖像,一個好方法是創建一個SKTexture,將CIFilter(如在這種情況下可能爲CILinearGradient)應用到基本框圖像,然後從該SKTexture創建SKSpriteNode

0

Matt的回答是正確的,但我無法添加漸變。這是我的嘗試,如果有人知道如何使其工作,請更新爲線程。

這裏是Core Image Ref

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); 

來測試您的過濾器的另一種好方法,是從2013年WWDC

+0

我能夠創建一個漸變我們CAGradientLayer和創建一個UIImage上下文,渲染層,並從UIImage創建紋理,速度很快,而且我沒有經歷任何減速(但我只需要爲按鈕創建一個)。 – AwDogsGo2Heaven

+0

@ AwDogsGo2Heaven您可以添加該代碼作爲答案。 – DogCoffee

+1

我在上面添加了答案。 – AwDogsGo2Heaven

6

下載演示程序CIFunHouse這裏是一個解決方案。 (請注意,我用的Rubymotion,紅寶石的目標C/iOS的結合,但邏輯是完全一樣的。如果有人想編輯這個並把客觀等價的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) 
+0

謝謝,但這不適用於OSX:Sprite Kit。它僅限於iOS。 – Jonny

+0

反正理由呢? – AwDogsGo2Heaven

+1

UIGraphicsBeginImageContextWithOptions不存在。 – Jonny

4

確定這裏是我現在正在使用的東西,我將它基於AwDogsGo2Heaven的解決方案,但是適用於Mac,這對於一個完全兼容的解決方案來說是甜蜜的,我很難確定如何創建上下文,但似乎工作,並且我不確定這個規模。在視網膜mac和非視網膜mac上運行,但看不到任何問題,但上下文是使用scale 2創建的,所以對於非視網膜mac可能是矯枉過正,我把它放在SKTexture上的一個類別中

爲了使用它,只需撥打+(SKTexture*)gradientWithSize:(const CGSize)SIZE colors:(NSArray*)colors

編輯:更新後的代碼和更多的討論在這裏:Gradient texture has wrong scale on retina Mac