Skip to content

Instantly share code, notes, and snippets.

@flatpickles
Last active July 15, 2018 20:42
Show Gist options
  • Save flatpickles/413642637ebd0b00fe2b to your computer and use it in GitHub Desktop.
Save flatpickles/413642637ebd0b00fe2b to your computer and use it in GitHub Desktop.
SKShapeNode scales a fill texture by default, instead of repeating the pattern. This snippet extends SKShapeNode to support setting a tiled fill-texture.
import SpriteKit
extension SKShapeNode {
func setTiledFillTexture(imageName: String, tileSize: CGSize) {
let targetDimension = max(self.frame.size.width, self.frame.size.height)
let targetSize = CGSizeMake(targetDimension, targetDimension)
let targetRef = UIImage(named: imageName).CGImage
UIGraphicsBeginImageContext(targetSize)
let contextRef = UIGraphicsGetCurrentContext()
CGContextDrawTiledImage(contextRef, CGRect(origin: CGPointZero, size: tileSize), targetRef)
let tiledTexture = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.fillTexture = SKTexture(image: tiledTexture)
}
}
@RolandColored
Copy link

I share my experiences to help others save some time. 😄
First, try not to get confused with fillTexture and strokeTexture. If you are drawing not a closed shape, like a path, then there is nothing to fill.
Also it looks to me like the texture image must have dimensions of 2^n. If I used different sizes the result is just a black fill.

@McNight
Copy link

McNight commented May 4, 2018

Thank you @RolandColored 👍

@Sunrise17
Copy link

can i cover ball with my texture image using this code?

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