I am creating a space exploration game using SpriteKit and Swift. I am generating a space environment using Core Graphics. Since the player can control a spaceship which can move in every direction, I am creating 9 different backgrounds and positioning them around the users ship like this.
7 8 9
4 5 6
1 2 3
Player start in layer 5. My game uses 2048x1536 screen with aspectFill so I can support all resolutions.
I generate background with this code.
UIGraphicsBeginImageContext(CGSizeMake(width, height))
let ctx = UIGraphicsGetCurrentContext();
let max = width * height / CGFloat(starCountModifier)
for i in 0...Int(max)
{
let x = arc4random_uniform(UInt32(width))
let y = arc4random_uniform(UInt32(height))
let alpha = CGFloat(Float(arc4random()) / Float(UINT32_MAX))
CGContextSetFillColorWithColor(ctx, SKColor(red: 1.0, green: 1.0, blue: 1.0, alpha: alpha * alpha * alpha).CGColor)
CGContextFillRect(ctx, CGRect(x: CGFloat(x), y: CGFloat(y), width: 2, height: 2))
}
let textureImage: UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
let texture = SKTexture(CGImage: textureImage.CGImage)
let sprite = SKSpriteNode(texture: texture)
addChild(sprite)
It works fine with one problem. Every background I create costs about 20-25mb of memory!
Even if I dont draw stars, it alone allocates this much memory by just creating SKSpriteNode out of that context.
Is there any way to optimize this texture data?
Thanks.