Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Gradient in Spritekit?

Tags:

sprite-kit

Is there any possible way to create a gradient filled box in SpriteKit? I've tried filling a shape node with that but it notes that only solid colors work with skshapenode.

like image 753
AwDogsGo2Heaven Avatar asked Oct 08 '13 18:10

AwDogsGo2Heaven


3 Answers

I don't think this is possible with current SKShapeNode, which barely handles its basic features currently. A good approach if you don't want to use pre-existing sprite gradient images would be to create an SKTexture from applying a CIFilter (like maybe CILinearGradient in this case) to a basic box image, and then create the SKSpriteNode from that SKTexture.

like image 73
Matt Avatar answered Nov 05 '22 12:11

Matt


Here is a solution. (Note, I am using Rubymotion, a ruby binding for Objective C / iOS, however the logic is exactly the same. If someone wants to edit this and put the objective c equivalent, go ahead

  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)
like image 6
AwDogsGo2Heaven Avatar answered Nov 05 '22 11:11

AwDogsGo2Heaven


OK here is something I am using now. I based it on AwDogsGo2Heaven's solution, however adapted for Mac. Would be sweet with one fully compatible solution. I am far from sure how to create contexts. But seems to work. Also I am unsure about the scale. Running on retina mac and non retina mac and can't see any problems but the context is created using scale 2 so might be overkill for non retina macs. I put this in a category on SKTexture.

In order use it, just call +(SKTexture*)gradientWithSize:(const CGSize)SIZE colors:(NSArray*)colors.

Edit: Updated code and more discussion here: Gradient texture has wrong scale on retina Mac

like image 4
Jonny Avatar answered Nov 05 '22 10:11

Jonny