Skip to content

Instantly share code, notes, and snippets.

@zooyf
Created August 26, 2017 05:17
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save zooyf/05a7a05cb02f90ec56b836a2467277a9 to your computer and use it in GitHub Desktop.
// NSAttributedString: Fit image to container
// Find answer in here:
// https://stackoverflow.com/questions/28920795/nsattributedstring-fit-image-to-container/29060169#29060169
## Code Below | Swift 3
let data = htmlString.data(using: .unicode)
let text = try NSMutableAttributedString(data: data!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil)
text.enumerateAttribute(NSAttachmentAttributeName, in: NSMakeRange(0, text.length), options: .init(rawValue: 0), using: { (value, range, stop) in
if let attachement = value as? NSTextAttachment {
let image = attachement.image(forBounds: attachement.bounds, textContainer: NSTextContainer(), characterIndex: range.location)!
let screenSize: CGRect = UIScreen.main.bounds
if image.size.width > screenSize.width-20 {
let scale = (screenSize.width-20)/image.size.width
let newImage = image.resizeImage(scale: scale)
let newAttribut = NSTextAttachment()
newAttribut.image = newImage
text.addAttribute(NSAttachmentAttributeName, value: newAttribut, range: range)
}
}
})
label.attributedText = text
extension UIImage {
func resizeImage(scale: CGFloat) -> UIImage {
let newSize = CGSize(width: self.size.width*scale, height: self.size.height*scale)
let rect = CGRect(origin: CGPoint.zero, size: newSize)
UIGraphicsBeginImageContext(newSize)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment