Как создать UIImage из пользовательского текста в Swift
Я пытаюсь создать UIImage
из пользовательского текста в Swift3
,
С помощью iOS Controls
Можно создать UIImage, ниже приведен код:
class func imageWithText(txtField: UITextField) -> UIImage {
UIGraphicsBeginImageContextWithOptions(txtField.bounds.size, false, 0.0)
txtField.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
Примечание: я знаю, что можно также добавить текст к изображению, но я не хочу делать это так.
Может ли кто-нибудь помочь мне решить эту проблему? Спасибо!
3 ответа
Вы можете использовать эту функцию, вы можете отправить любой текст этой функции, внутри нее я создаю UILabile и устанавливаю атрибут текста как вам нравится
func imageWith(name: String?) -> UIImage? {
let frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let nameLabel = UILabel(frame: frame)
nameLabel.textAlignment = .center
nameLabel.backgroundColor = .lightGray
nameLabel.textColor = .white
nameLabel.font = UIFont.boldSystemFont(ofSize: 40)
nameLabel.text = name
UIGraphicsBeginImageContext(frame.size)
if let currentContext = UIGraphicsGetCurrentContext() {
nameLabel.layer.render(in: currentContext)
let nameImage = UIGraphicsGetImageFromCurrentImageContext()
return nameImage
}
return nil
}
Я использую следующее String
расширение для изготовления UIImage
экземпляры из строки и, без необходимости элементов управления пользовательского интерфейса, таких как UITextField
или же UILabel
и я использую это так:
var image: UIImage? =
"Test".image(withAttributes: [
.foregroundColor: UIColor.red,
.font: UIFont.systemFont(ofSize: 30.0),
], size: CGSize(width: 300.0, height: 80.0)
// Or
image = "Test".image(withAttributes: [.font: UIFont.systemFont(ofSize: 80.0)])
// Or
image = "Test".image(size: CGSize(width: 300.0, height: 80.0))
// Or even just
image = "Test".image()
Ниже приведены две возможные реализации для достижения желаемого эффекта, продемонстрированного выше.
Метод UIGraphicsImageRenderer (более производительный)
extension String {
/// Generates a `UIImage` instance from this string using a specified
/// attributes and size.
///
/// - Parameters:
/// - attributes: to draw this string with. Default is `nil`.
/// - size: of the image to return.
/// - Returns: a `UIImage` instance from this string using a specified
/// attributes and size, or `nil` if the operation fails.
func image(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize? = nil) -> UIImage? {
let size = size ?? (self as NSString).size(withAttributes: attributes)
return UIGraphicsImageRenderer(size: size).image { _ in
(self as NSString).draw(in: CGRect(origin: .zero, size: size),
withAttributes: attributes)
}
}
}
Метод UIGraphicsImageContext (старая школа)
extension String {
/// Generates a `UIImage` instance from this string using a specified
/// attributes and size.
///
/// - Parameters:
/// - attributes: to draw this string with. Default is `nil`.
/// - size: of the image to return.
/// - Returns: a `UIImage` instance from this string using a specified
/// attributes and size, or `nil` if the operation fails.
func image(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize? = nil) -> UIImage? {
let size = size ?? (self as NSString).size(withAttributes: attributes)
UIGraphicsBeginImageContext(size)
(self as NSString).draw(in: CGRect(origin: .zero, size: size),
withAttributes: attributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
В этом очень старом вопросе, честно говоря, теперь все так просто:
Сделайте квадрат цвета:
let image = UIGraphicsImageRenderer(size: size).image { rendererContext in
UIColor.yellow.setFill()
rendererContext.fill(rect)
}
Добавить текст сегодня очень просто:
let image = UIGraphicsImageRenderer(size: sz).image { rendererContext in
UIColor.yellow.setFill()
rendererContext.fill(rect)
"fattie".draw(in: rect)
}
Вот и все.
"some text".draw(in: rect)
Чтобы установить масштаб (вероятно, «1»), шрифт, бла-бла и т.д…
let sz = CGSize(width: 500, height: 300)
let frame = CGRect(origin: .zero, size: sz).insetBy(dx: 40, dy: 40)
let fmt = UIGraphicsImageRendererFormat()
fmt.scale = 1
let att = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 50.0)]
let image = UIGraphicsImageRenderer(size: sz, format: fmt).image { rendererContext in
UIColor.systemYellow.setFill()
rendererContext.fill(CGRect(origin: .zero, size: sz))
"fattie?!".draw(in: frame, withAttributes: att)
}
if let data = image.jpegData(compressionQuality: 0.4) {
let pp = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let ff = pp.appendingPathComponent("example.jpg")
try? data.write(to: ff)
print("On your mac look in: \(pp.path)")
}
хорошо?