问题
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?
来源:https://stackoverflow.com/questions/29886540/how-to-get-the-original-image-scale-from-an-sktexture