Created
August 1, 2017 21:07
-
-
Save erica/f4e62f046c07806d81a150dfdd5e7256 to your computer and use it in GitHub Desktop.
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
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