0
let dotGeometry = SCNSphere(radius: 0.0005)
let dotNode = SCNNode(geometry: dotGeometry)
dotNode.position = dotPosition
if let image = imageWithText(text: "\(index)", fontSize:20, imageSize: CGSize(width:100,height:100), backgroundColor: .cyan) {
    dotGeometry.firstMaterial?.diffuse.contents = image
}
self.rootNode.addChildNode(dotNode)

我使用上面的代码来创建一个几何图形,然后用下面的代码创建的文本图像包装它SCNNodeSCNSphere

除了当用户开始旋转场景时,这一切都有效,球体随着场景旋转并且文本移动到球体的后面,超出了用户的视野。

func imageWithText(text:String, fontSize:CGFloat, 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 = [
        NSAttributedString.Key.font: UIFont(name: "Arial-BoldMT", size:fontSize),
        NSAttributedString.Key.paragraphStyle: paragraphStyle,
        NSAttributedString.Key.foregroundColor: fontColor
    ]

    // Determine the width/height of the text for the attributes
    let textSize = text.size(withAttributes: attributes as [NSAttributedString.Key : Any])

// 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 as [NSAttributedString.Key : Any])

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

我怎样才能让文本始终在用户的视图中,即不让文本随着相机/场景旋转而旋转?

4

1 回答 1

0

最后通过dotNode.constraints = [SCNBillboardConstraint()]在创建后添加来完成此操作dotNode

于 2018-10-26T02:10:14.437 回答