首页 > 解决方案 > 在图形上下文中保留颜色

问题描述

我有UILabel一个NSMutableAttributedString: foregroundColorUIColor.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?

标签: swiftuikit

解决方案


信不信由你,属性字符串知道如何绘制自己,所以你可以写:

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

推荐阅读