Skip to content

Instantly share code, notes, and snippets.

@Tantas
Last active July 19, 2022 09:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Tantas/7fc01803d6b559da48d6 to your computer and use it in GitHub Desktop.
Save Tantas/7fc01803d6b559da48d6 to your computer and use it in GitHub Desktop.
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
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"

@craiggrummitt
Copy link

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

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