Created
August 26, 2017 05:17
Star
You must be signed in to star a gist
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
// 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