How to create a Gradient in Spritekit?

前端 未结 4 727
长发绾君心
长发绾君心 2021-02-08 22:35

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.

4条回答
  •  爱一瞬间的悲伤
    2021-02-08 23:08

    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)
    

提交回复
热议问题