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)
I am using the above code to create a SCNNode
with SCNSphere
geometry and then wrap it with the image of text created with below code:
It all works except when user starts rotating the scene, the sphere rotates with the scene and text moves to the back of the sphere out of user's view.
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
}
How can I keep the text always in user's view i.e. not let the text rotate with the camera/scene rotation?
Finally accomplished this by adding dotNode.constraints = [SCNBillboardConstraint()]
after creating dotNode
.