簡體   English   中英

在SceneKit中跨球體繪制文本

[英]Drawing text across sphere in SceneKit

我剛開始在我的UIKit應用程序中使用SceneKit,目的是顯示和操作一些3D模型。 我需要顯示一個球體,上面寫着一些短文。 我正在渲染這樣的球體:

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來實現我的需求,但我沒有運氣。 這樣做的正確方法是什么?

您可以通過創建包含文本的圖像來圍繞對象的表面包裝文本,例如,

在此輸入圖像描述

然后加載並將圖像分配給diffuse的contents屬性

    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)

在此輸入圖像描述

或者,您可以通過編程方式創建帶有文本的圖像

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM