Swift根据文字返回颜色

204 阅读1分钟
/// 根据文字返回颜色
func color(from text: String, textColor: UIColor, backgroundColor: UIColor) -> UIColor {
    /// view -> image
    func image(from view: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0);
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
    // frame 使用实际大小
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    label.font = .systemFont(ofSize: 16)
    label.text = text
    label.textColor = textColor
    label.backgroundColor = backgroundColor
    label.textAlignment = .center

    return UIColor(patternImage: image(from: label)!)
}