Skip to content

Instantly share code, notes, and snippets.

Embed
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: http://ios7colors.com/.
Example:
(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
topColor:topColor
bottomColor:bottomColor];
SKSpriteNode* backgroundGradient = [[SKSpriteNode alloc] initWithTexture:backgroundTexture];
backgroundGradient.position = CGPointMake(self.size.width/2, self.size.height/2);
[self addChild:backgroundGradient];
*/
+(SKTexture*)textureWithVerticalGradientofSize:(CGSize)size
topColor:(CIColor*)topColor
bottomColor:(CIColor*)bottomColor;
@end
#import "SKTexture+Gradient.h"
@implementation SKTexture (Gradient)
+(SKTexture*)textureWithVerticalGradientofSize:(CGSize)size
topColor:(CIColor*)topColor
bottomColor:(CIColor*)bottomColor
{
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]];
}
@end
@ncsolar

This comment has been minimized.

Copy link

@ncsolar 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"

@craiggrummitt

This comment has been minimized.

Copy link

@craiggrummitt craiggrummitt commented Mar 24, 2015

Thanks for this! I've added gradient directions and converted to Swift here:
https://gist.github.com/craiggrummitt/ad855e358004b5480960

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