2017-06-17 95 views
1

我剛開始在我的UIKit應用程序中使用SceneKit,目的是顯示和操作一些3D模型。我需要展示一個包含一些簡短文字的球體。我渲染領域是這樣的:在SceneKit中跨球體繪製文本

let sphereGeometry = SCNSphere(radius: 1) 
let sphereNode = SCNNode(geometry: sphereGeometry) 
sphereNode.position = SCNVector3(x: -1, y: 0, z: 8) 
sphereGeometry.firstMaterial?.diffuse.contents = UIColor.cyan 

self.rootNode.addChildNode(sphereNode) 

我試圖用一個CATextLayer實現我需要什麼,但我有一點運氣。什麼是正確的方法來做到這一點?

+0

適用於球? – 0x141E

+0

@ 0x141E基本上是的,我需要它成爲球體表面的一部分 –

回答

5

可以通過創建包含文本的圖像,例如包裹的物體的表面周圍的文本,

enter image description here

,然後加載和通過

let sphereGeometry = SCNSphere(radius: 1) 
    let sphereNode = SCNNode(geometry: sphereGeometry) 
    sphereNode.position = SCNVector3(x: 0, y: 0, z: 0) 

    if let textImage = UIImage(named:"TextImage") { 
     sphereGeometry.firstMaterial?.diffuse.contents = textImage 
    } 

    scene.rootNode.addChildNode(sphereNode) 
分配圖像到漫的 contents屬性

enter image description here

或者,您可以通過編程方式創建一個i通過

func imageWithText(text:String, fontSize:CGFloat = 150, fontColor:UIColor = .black, imageSize:CGSize, backgroundColor:UIColor) -> UIImage? { 

    let imageRect = CGRect(origin: CGPoint.zero, size: imageSize) 
    UIGraphicsBeginImageContext(imageSize) 

    defer { 
     UIGraphicsEndImageContext() 
    } 

    guard let context = UIGraphicsGetCurrentContext() else { 
     return nil 
    } 

    // Fill the background with a color 
    context.setFillColor(backgroundColor.cgColor) 
    context.fill(imageRect) 

    let paragraphStyle = NSMutableParagraphStyle() 
    paragraphStyle.alignment = .center 

    // Define the attributes of the text 
    let attributes = [ 
     NSFontAttributeName: UIFont(name: "TimesNewRomanPS-BoldMT", size:fontSize), 
     NSParagraphStyleAttributeName: paragraphStyle, 
     NSForegroundColorAttributeName: fontColor 
    ] 

    // Determine the width/height of the text for the attributes 
    let textSize = text.size(attributes: attributes) 

    // Draw text in the current context 
    text.draw(at: CGPoint(x: imageSize.width/2 - textSize.width/2, y: imageSize.height/2 - textSize.height/2), withAttributes: attributes) 

    if let image = UIGraphicsGetImageFromCurrentImageContext() { 
     return image 
    } 
    return nil 
} 

文本法師和你想要的文字環繞球體圖像與

let sphereGeometry = SCNSphere(radius: 1) 
    let sphereNode = SCNNode(geometry: sphereGeometry) 
    sphereNode.position = SCNVector3(x: 0, y: 0, z: 0) 

    if let image = imageWithText(text: "Hello, World!", imageSize: CGSize(width:1024,height:1024), backgroundColor: .cyan) { 
     sphereGeometry.firstMaterial?.diffuse.contents = image 
    } 

    scene.rootNode.addChildNode(sphereNode) 
+0

出色地工作!謝謝! –

+0

當要顯示的文本的屬性被指定時,是否有辦法使它將文本呈現爲HTML?我正在爲UILabel做一些類似的設置'documentType'屬性的自定義'setHTML'方法。 –

+0

我找不到任何可以讓你做到的事情。也許你可以用'NSAttributedString'完成相同或類似的事情。 – 0x141E