2

I'm using sprite-kit in Swift and setting up textures using the SKTexture(rect:inTexture:) function. I am not using built-in texture atlases, instead I am creating the parent texture (the texture atlas) using SKTexture(imageNamed:). This is because I already have atlases and sub-texture positions (in pixels) in my data files, not separate images.

So the .size() of the SKTexture object is correct when the image is @2x (the size is half of the pixel dimensions). I calculate the sub-rect coordinates (which are in unit coordinates, 0-1) by dividing by the size, but I need to know the original image scale so that I can divide my pixel-dimensions by it.

Here is my code that works nicely:

// Create the texture as a sub-rect of the parent texture
if  let parentTexture = textures[parentTextureId] {
    let size = parentTexture.size()
    var subRect = CGRectFromString(subRectString)
    subRect = CGRectMake(
        (subRect.origin.x / 2) / size.width,
        (size.height - ((subRect.origin.y / 2) + (subRect.size.height / 2))) / size.height,
        (subRect.size.width / 2) / size.width,
        (subRect.size.height / 2) / size.height)
    let texture = SKTexture(rect: subRect, inTexture: parentTexture)
    textures[textureId] = texture
}

The problem is that I have had to hard-code in all those / 2 adjustments for the scale. How can I get the original image scale (or the actual pixel dimensions) of the texture so that I can calculate the sub-rect correctly without hard-coding?

jhabbott
  • 18,461
  • 9
  • 58
  • 95
  • If you are creating your own texture atlas image, shouldn't you already know the size for each sub image? – sangony Apr 27 '15 at 12:20
  • Yes - I know the size in pixels, but I don't know the scale of the image in the generic code that should be capable of loading 1x or 2x images (depending what's available) on 1x or 2x displays. – jhabbott Apr 27 '15 at 19:47

0 Answers0