Skip to content

Instantly share code, notes, and snippets.

@erica
Created August 1, 2017 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/f4e62f046c07806d81a150dfdd5e7256 to your computer and use it in GitHub Desktop.
Save erica/f4e62f046c07806d81a150dfdd5e7256 to your computer and use it in GitHub Desktop.
import UIKit
extension String {
func toAttributed() -> NSAttributedString {
return NSAttributedString(string: self)
}
}
extension NSAttributedString {
func toImage(withAlpha alpha: CGFloat = 1.0) -> UIImage {
return UIGraphicsImageRenderer(size: self.size())
.image { context in
context.cgContext.setAlpha(alpha)
self.draw(at: .zero)
}
}
func renderToAttachment(withAlpha alpha: CGFloat = 1.0) -> NSAttributedString {
let image = self.toImage()
let attachment: NSTextAttachment = {
$0.image = image
$0.bounds = CGRect(origin: .zero, size: image.size)
return $0
}(NSTextAttachment())
return NSAttributedString(attachment: attachment)
}
}
let string = NSMutableAttributedString(string: "")
string.append("πŸ˜€πŸ˜€πŸ˜€".toAttributed().renderToAttachment())
string.append("πŸ˜€πŸ˜€πŸ˜€".toAttributed().renderToAttachment(withAlpha: 0.5))
string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment