2016-11-07 7 views
1

SpriteKit에 머물면서 TextKit이 제공하는 훨씬 더 큰 컨트롤을 사용하여 더 "예술적"텍스트를 만들 수 있습니까? 그렇다면이 문자열을 이미지로 변환하여 SKSpriteNodes로 사용할 수 있습니까?SKLabel을 피하고 대신 TextKit을 사용하여 SKTexture를 만드시겠습니까?

좀 더 진지한 커닝 소재를 사용하고 싶습니다. 훨씬 더 큰 간격과 SKLabels에서는 가능하지 않지만 TextKit의 일부인 다른 몇 가지 사항이 있습니다. 그들이 내가 원하는 방식으로 보이도록 끝내자 마자 비트 맵이 될 수 있습니다.

그러나 TextKit을 이미지로 변환하는 방법을 찾을 수 없습니다.

+0

이 내가 ** ** 정적을지지 것 @MobileBen 동적 텍스트 또는 정적 –

+0

에 대한인가, 다음, 어쩌면 할 수있는 방법을 찾아 동적 텍스트에 대해 작동하게하십시오. – Nik

+0

예, 정적 텍스트 콘텐츠입니다.하지만 그로 인해 최종 비트 맵이 이동하고 크기가 조정됩니다. – Confused

답변

2

텍스트를 CGContext에 그 다음 텍스처를 만들고 SKSpriteNode에 해당 텍스처를 지정할 수 있습니다. 여기

this GitHub project에서 예입니다 : 그 짓을하고 파악 된 후에는

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() 
    } 

} 
+0

대단히 감사합니다. 'guard let ...'을 사용하는 훌륭한 예는 방금 깨달은 것 중 아주 멋진 도구 일 것입니다. 'let let ...'보다 훨씬 좋네요! – Confused