swift - 在图形上下文中保留颜色
问题描述
我有UILabel
一个NSMutableAttributedString
: foregroundColor
。UIColor.red
我希望将标签呈现为UIImage
同时保留其原始颜色,但它呈现为黑色。
extension NSMutableAttributedString {
func title(_ text: String, color: UIColor) {
let attr = [NSAttributedString.Key.foregroundColor: color]
let str = NSMutableAttributedString(string: text, attributes: attr)
append(str)
}
}
extension UIImage {
class func imageWithLabel(label: UILabel) -> UIImage {
UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0.0)
label.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
let formattedString = NSMutableAttributedString()
formattedString.title("Hello, world", color: .red)
label.attributedText = formattedString
let image = UIImage.imageWithLabel(label: label) // returns a black label
如何在 中保留标签的红色前景色UIImage?
?
解决方案
信不信由你,属性字符串知道如何绘制自己,所以你可以写:
extension UIImage {
class func imageWithLabel(label: UILabel) -> UIImage {
return UIGraphicsImageRenderer(bounds: label.bounds).image { _ in
label.attributedText?.draw(in: label.bounds)
}
}
}
但由于您甚至不需要标签,您可以这样做:
extension NSAttributedString {
func image(size: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
self.draw(at: .zero)
}
}
}
请参阅绘图上的苹果文档
这是一个游乐场:
import UIKit
import PlaygroundSupport
import UIKit
import PlaygroundSupport
extension NSMutableAttributedString {
func title(_ text: String, color: UIColor) {
let attr = [NSAttributedString.Key.foregroundColor: color]
let str = NSMutableAttributedString(string: text, attributes: attr)
append(str)
}
}
extension NSAttributedString {
func image(size: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
self.draw(at: .zero)
}
}
}
let segmentedControl = UISegmentedControl.init(frame: .init(origin: .zero, size: .init(width: 160, height: 20)))
let formattedString = NSMutableAttributedString()
formattedString.title("Hello, world", color: .red)
let image = formattedString.image(size: .init(width: 60, height: 20))
segmentedControl.insertSegment(with: image.withRenderingMode(.alwaysOriginal), at: 0, animated: false)
segmentedControl.insertSegment(withTitle: "test", at: 1, animated: false)
segmentedControl.backgroundColor = .white
PlaygroundPage.current.liveView = segmentedControl
推荐阅读
- algorithm - 如何设置hashtable的阈值,避免频繁rehash?
- magento - Magento 2 REST API。列出具有父/子关系的产品
- tcp - erlang VM 占用大约 600 个 os/windows 机器线程
- javascript - 简单赋值帮助:调用函数向其传递参数并获取其返回值
- javascript - 异步方法返回未定义
- python - Extracting a numerical value from .csv files
- wordpress - 将自定义属性添加到联系表单本身(wordpress 插件)
- javascript - How to assign the query responses to the global.arrays, not the value inside the array of global.arrays?
- javascript - express js 无法获取/注册
- java - 删除单个链表上的节点的最有效方法?