在我的项目中,纹理是通过PaintCode ( paint-code ) 提供的方法按程序生成的。
然后我创建一个 SKTextureAtlas
来自归档为 UIImage
的字典通过这些方法生成:
myAtlas = SKTextureAtlas(dictionary: myTextures)
最后,使用textureNamed
从atlas检索纹理 :
var sprite1 = SKSpriteNode(texture:myAtlas.textureNamed("texture1"))
但是在 iPhone4S 模拟器上显示的节点是双倍大小的。 iPhone 6 Plus 模拟器上的尺寸为三倍。
似乎在初始化时,atlas 以设备分辨率计算图像。 但生成的图像已经具有正确的尺寸,不需要更改。请参阅下面的绘图方法。
以下是生成图像的描述:
<UIImage: 0x7f86cae56cd0>, {52, 52}
以及图集中对应纹理的描述:
<SKTexture> 'image1' (156 x 156)
这适用于 iPhone 6 Plus,使用 @3x 图像,这就是尺寸为 x3 的原因。
对于 iPhone 4S,使用 @2x 图像,正如预期的那样:
<UIImage: 0x7d55dde0>, {52, 52}
<SKTexture> 'image1' (156 x 156)
最后,scale
生成的属性 UIImage
设置为正确的设备分辨率:@2x (iPhone 4S) 为 2.0,@3x (iPhone 6 Plus) 为 3.0。
问题
那么我该怎么做才能避免图集调整图片大小呢?
绘制方法
PaintCode生成绘图方法如下:
public class func imageOfCell(#frame: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
StyleKit.drawCell(frame: frame)
let imageOfCell = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return imageOfCell
}
更新 1
比较两种生成 SKTextureAtlas
的方法
// Some test image
let testImage:UIImage...
// Atlas creation
var myTextures = [String:UIImage]()
myTextures["texture1"] = testImage
myAtlas = SKTextureAtlas(dictionary: myTextures)
// Create two textures from the same image
let texture1 = myAtlas.textureNamed("texture1")
let texture2 = SKTexture(image:testImage)
// Wrong display : node is oversized
var sprite1 = SKSpriteNode(texture:texture1)
// Correct display
var sprite2 = SKSpriteNode(texture:texture2)
看来问题出在SKTextureAtlas
上来自字典如SKSpriteNode
初始化不使用 UIImage
中的 scale 属性正确调整节点大小。
以下是控制台上的说明: - 纹理 1:'' (84 x 84) - 纹理2:'纹理1'(84 x 84)
texture2
怀念一些data
!这可以解释缺乏规模信息来正确调整节点大小:
节点的大小 = 纹理的大小除以纹理的比例。
更新2
当UIImage
的scale属性出现时会出现此问题与一个不同。
所以可以使用下面的方法来生成图片:
func imageOfCell(frame: CGRect, color:SKColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
var bezierPath = UIBezierPath(rect: frame)
color.setFill()
bezierPath.fill()
let imageOfCell = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return imageOfCell
}
最佳答案
问题来自于使用SKTextureAtlas(dictionary:)
初始化图集。
使用此方法创建的 SKTexture 不会嵌入与图像的scale属性相关的数据。因此,在 init(texture:)
创建 SKSpriteNode
过程中,纹理中缺少比例信息,导致选择纹理的大小来代替图像的大小。
纠正它的一种方法是在 SKSpriteNode
创建期间提供节点的大小:init(texture:size:)
关于swift - 如何强制从字典创建的 SKTextureAtlas 不修改纹理大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31557305/