Last active
December 25, 2021 15:36
-
-
Save tomasen/9a96bb1f8202f1ebc3de6f6035762cff to your computer and use it in GitHub Desktop.
word cloud image view demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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