ios - 带有颜色和居中文本的 UIImage

标签 ios swift uiimage uilabel uigraphicscontext

我正在尝试向 UIImage 添加一个方便的初始化程序,这将允许我创建一个图像,其中给定的文本居中,并给定背景颜色:

我有以下代码:

public convenience init?(color: UIColor, withText: String, withTextColor: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
    let rect = CGRect(origin: .zero, size: size)
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
    color.setFill()
    UIRectFill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    let label = UILabel()
    label.text = withText
    label.textAlignment = .center
    label.font = UIFont.boldSystemFont(ofSize: 40)
    label.textColor = withTextColor


    guard let cgImage = image?.cgImage else { return nil }
    self.init(cgImage: cgImage)
}

这会创建具有正确背景颜色的图像 - 但我不确定如何将 UILabel 嵌入图像中间。

编辑

enter image description here

最佳答案

属性字符串知道如何to draw themselves ,所以你不需要标签。他们还可以 tell you how big they are甚至包裹以适合可用的宽度。这是 Playground ,展示了如何从任何属性字符串获取图像:

import UIKit
import PlaygroundSupport

extension NSAttributedString {
  func asImage(size: CGSize = .init(width: .max, height: .max)) -> UIImage {
    UIGraphicsImageRenderer(bounds: boundingRect(with: size, options: [.usesLineFragmentOrigin], context: nil)).image { context in
      self.draw(at: .zero)
    }
  }
}

let attributedString = NSAttributedString.init(string: "testing", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
let image = attributedString.asImage()
let imageView = UIImageView(image: image)
PlaygroundPage.current.liveView = imageView

关于ios - 带有颜色和居中文本的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58278226/

相关文章:

ios - TableView 复选框不接受索引 0 的操作

ios - 使用 UILabel 的子类覆盖 UIButton 中的 titleLabel

swift - 从 iPhone 访问 UIImage 时出错,但从 Xcode 模拟器访问时出错

ios - iOS SDK 中集成的 Mixpanel 不发送事件

ios - 为iphone应用程序添加ipad界面

ios - 侧边菜单 revealcontroller 问题与 UITableViewController

ios - 由 UIDocumentInteractionController (iOS 10.3) 打开时出现空白或半加载的 PDF

iphone - iPad : UIImage imageWithContentsOfFile performance problems

iphone - 如何在 ios 中创建自己的面具

objective-c - 警告弹出窗口让用户知道 iOS 5 之前的版本不受官方支持