在SpriteKit中,是否有可能用TextKit提供的更大的控件创建更多的“艺术”文本,然后(以某种方式)将这些字符串转换成图像,以便它们可以用作SKSpriteNodes?
我问是因为我想做些更严肃的事.更大的间距,还有一些SKLabels不可能实现的东西,但它们是TextKit的一部分,但我希望它们成为位图,让它们看起来像我想要的那样。
但我找不到办法把TextKit变成图像。
发布于 2016-11-12 17:41:36
您可以在CGContext中绘制文本,然后从它创建纹理并将该纹理分配给SKSpriteNode。
下面是来自这个GitHub项目的一个示例
class ASAttributedLabelNode: SKSpriteNode {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(size: CGSize) {
super.init(texture: nil, color: UIColor.clear, size: size)
}
var attributedString: NSAttributedString! {
didSet {
draw()
}
}
func draw() {
guard let attrStr = attributedString else {
texture = nil
return
}
let scaleFactor = UIScreen.main.scale
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
guard let context = CGContext(data: nil, width: Int(size.width * scaleFactor), height: Int(size.height * scaleFactor), bitsPerComponent: 8, bytesPerRow: Int(size.width * scaleFactor) * 4, space: colorSpace, bitmapInfo: bitmapInfo) else {
return
}
context.scaleBy(x: scaleFactor, y: scaleFactor)
context.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
UIGraphicsPushContext(context)
let strHeight = attrStr.boundingRect(with: size, options: .usesLineFragmentOrigin, context: nil).height
let yOffset = (size.height - strHeight) / 2.0
attrStr.draw(with: CGRect(x: 0, y: yOffset, width: size.width, height: strHeight), options: .usesLineFragmentOrigin, context: nil)
if let imageRef = context.makeImage() {
texture = SKTexture(cgImage: imageRef)
} else {
texture = nil
}
UIGraphicsPopContext()
}
}https://stackoverflow.com/questions/40472026
复制相似问题