Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Creates a SKTexture programatically with a vertical gradient.
#import <SpriteKit/SpriteKit.h>
@interface SKTexture (Gradient)
/** Creates a SKTexture programatically with a vertical gradient.
Great suggestion for colors:
(Inside a SKScene class)
CIColor *topColor = [CIColor colorWithRed:1 green:0.369 blue:0.227 alpha:1];
CIColor *bottomColor = [CIColor colorWithRed:1 green:0.165 blue:0.408 alpha:1];
SKTexture* backgroundTexture = [SKTexture textureWithVerticalGradientofSize:self.size
SKSpriteNode* backgroundGradient = [[SKSpriteNode alloc] initWithTexture:backgroundTexture];
backgroundGradient.position = CGPointMake(self.size.width/2, self.size.height/2);
[self addChild:backgroundGradient];
#import "SKTexture+Gradient.h"
@implementation SKTexture (Gradient)
CIContext *coreImageContext = [CIContext contextWithOptions:nil];
CIFilter *gradientFilter = [CIFilter filterWithName:@"CILinearGradient"];
[gradientFilter setDefaults];
CIVector *startVector = [CIVector vectorWithX:size.width/2 Y:0];
CIVector *endVector = [CIVector vectorWithX:size.width/2 Y:size.height];
[gradientFilter setValue:startVector forKey:@"inputPoint0"];
[gradientFilter setValue:endVector forKey:@"inputPoint1"];
[gradientFilter setValue:bottomColor forKey:@"inputColor0"];
[gradientFilter setValue:topColor forKey:@"inputColor1"];
CGImageRef cgimg = [coreImageContext createCGImage:[gradientFilter outputImage]
fromRect:CGRectMake(0, 0, size.width, size.height)];
return [SKTexture textureWithImage:[UIImage imageWithCGImage:cgimg]];
Copy link

ncsolar commented Nov 14, 2014

Thanks for this class, while using it on a iPad II and iPhone 4S i get this error: "BSXPCMessage received error for message: Connection interrupted"

Copy link

craiggrummitt commented Mar 24, 2015

Thanks for this! I've added gradient directions and converted to Swift here:

Copy link

ghost commented Jul 16, 2021

Dont forget to #import <CoreImage/CoreImage.h>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment