Skip to content

Instantly share code, notes, and snippets.

@tomasen
Last active December 25, 2021 15:36
Show Gist options
  • Save tomasen/9a96bb1f8202f1ebc3de6f6035762cff to your computer and use it in GitHub Desktop.
Save tomasen/9a96bb1f8202f1ebc3de6f6035762cff to your computer and use it in GitHub Desktop.
word cloud image view demo
var body: some View {
Image(uiImage: wordCloudImage(words))
.resizable()
.aspectRatio(contentMode: .fit)
.padding(10)
}
func wordCloudImage(_ words: [WordElement]) -> UIImage {
UIGraphicsBeginImageContextWithOptions(canvasSize, false, 1.0)
var occupiedAreas = [CGRect]()
for word in words {
let textAttrs = [
NSAttributedString.Key.font: UIFont(name: word.fontName, size: word.fontSize)!,
NSAttributedString.Key.foregroundColor: word.color,
] as [NSAttributedString.Key : Any]
// calculate rendered size
let estimateSize = (word.text as NSString).size(withAttributes: textAttrs)
let textRect = findSafePlace(for: estimateSize, avoid: occupiedAreas)
word.text.draw(in: textRect, withAttributes: textAttrs)
occupiedAreas.append(textRect)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment