Last active
August 1, 2017 21:37
-
-
Save jeffreybergier/b0b0f7b5af3533f000b5e256f6be1077 to your computer and use it in GitHub Desktop.
Semi-transparent Emoji in NSAttributedString Workaround
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 NSAttributedString { | |
var image: UIImage { | |
let options: NSStringDrawingOptions = [ .usesLineFragmentOrigin, .usesFontLeading, .usesDeviceMetrics ] | |
let rect = boundingRect(with: self.size(), options: options, context: nil) | |
return UIGraphicsImageRenderer(bounds: rect).image { _ in | |
draw(at: .zero) | |
} | |
} | |
} | |
extension UIImage { | |
func with(alpha: CGFloat = 1.0) -> UIImage { | |
let format = UIGraphicsImageRendererFormat() | |
format.opaque = false | |
return UIGraphicsImageRenderer(size: self.size, format: format).image() { (context) in | |
draw(in: context.format.bounds, blendMode: .normal, alpha: alpha) | |
} | |
} | |
} | |
func renderStars(selectedStars: String, notYetSelectedStars: String) -> UIImage { | |
let selectedAttributes: [NSAttributedStringKey : Any] = [ | |
.foregroundColor : UIColor.blue.withAlphaComponent(1.0), | |
.font : UIFont.systemFont(ofSize: 50) | |
] | |
let selectedImage = NSAttributedString(string: selectedStars, attributes: selectedAttributes).image | |
let selectedAttachment = NSTextAttachment() | |
selectedAttachment.image = selectedImage | |
let notYetSelectedImage = NSAttributedString(string: notYetSelectedStars, attributes: selectedAttributes).image.with(alpha: 0.4) | |
let notYetSelectedAttachment = NSTextAttachment() | |
notYetSelectedAttachment.image = notYetSelectedImage | |
let string = NSMutableAttributedString() | |
string.append(NSAttributedString(attachment: selectedAttachment)) | |
string.append(NSAttributedString(attachment: notYetSelectedAttachment)) | |
let image = UIGraphicsImageRenderer(size: string.size()).image() { context in | |
string.draw(at: .zero) | |
} | |
return image | |
} | |
renderStars(selectedStars: "✪✪", notYetSelectedStars: "✪✪✪") | |
renderStars(selectedStars: "😖😖😖", notYetSelectedStars: "😖😖") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment