我有這樣的影像:

但是我想在這個影像下添加一些文本,并像一個新的 UIImage 一樣獲取它,例如:

據我了解,我應該創建一個新影像。然后將我的影像放入其中并添加文本。我該怎么做?
我試圖使用這樣的東西,但無法將我的文字放在影像下
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 12)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedStringKey.font: textFont,
NSAttributedStringKey.foregroundColor: textColor,
] as [NSAttributedStringKey : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
PS 我的影像背景清晰。紅色是另一種觀點的背景。
uj5u.com熱心網友回復:
通常,您應該始終顯示一些迄今為止您嘗試過的代碼。但這是一種微不足道的觀點,看起來應該類似于:
class ViewWithImage: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
fatalError("storyboards no thanks")
}
private func setup() {
backgroundColor = .red
let imageView = UIImageView()
imageView.image = UIImage(named: "garbagecan")
imageView.contentMode = .scaleAspectFit
imageView.tintColor = .white
let deleteLabel = UILabel()
deleteLabel.text = "Delete"
deleteLabel.textColor = .white
let vStack = UIStackView()
vStack.axis = .vertical
vStack.spacing = 8
addSubview(vStack)
NSLayoutConstraint.activate([
vStack.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16),
vStack.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16),
vStack.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -16),
vStack.topAnchor.constraint(equalTo: self.topAnchor, constant: 16)
])
vStack.addArrangedSubview(imageView)
vStack.addArrangedSubview(deleteLabel)
}
}
uj5u.com熱心網友回復:
如果您使用IOS 15將組件更改為 UIButton 沒有問題,那么未來有一個新的按鈕可以輕松做到這一點
let myButton = UIButton()
myButton.configuration?.image = UIImage(yourImage)
myButton.configuration?.imagePadding = 4 // for padding between image and text
muButton.configuration?.imagePlacement = .top // placement to image
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/337250.html
