我想在UIImage的右上角或右下角绘制文字。 我有一个扩展功能,可以很好地绘制文本,但问题是将文本放置在屏幕右侧(因为文本被剪切)。在图像右上角绘制文字
这里是扩展:
extension UIImage {
func addText(drawText: NSString, atPoint: CGPoint, textColor: UIColor?, textFont: UIFont?) -> UIImage{
// Setup the font specific variables
var _textColor: UIColor
if textColor == nil {
_textColor = UIColor.white
} else {
_textColor = textColor!
}
var _textFont: UIFont
if textFont == nil {
_textFont = UIFont.systemFont(ofSize: 50)
} else {
_textFont = textFont!
}
// Setup the image context using the passed image
UIGraphicsBeginImageContext(size)
// Setup the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: _textFont,
NSForegroundColorAttributeName: _textColor,
] as [String : Any]
// Put the image into a rectangle as large as the original image
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
// Create a point within the space that is as bit as the image
let rect = CGRect(x: atPoint.x, y: atPoint.y, width: size.width, height: size.height)
// Draw the text into an image
drawText.draw(in: rect, withAttributes: textFontAttributes)
// Create a new image out of the images we have created
let newImage = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//Pass the image back up to the caller
return newImage!
}
}
问题是,如果文本太长或太大,它会在屏幕中。我需要改变原点,将文本从右侧写入左侧,这样只会在屏幕左侧和右侧留出空间。我怎么能这样做?
将标签添加为子视图并创建imageView的“sceenshot”可能更容易。 [这是如何](https://stackoverflow.com/q/2214957/1457385)。 – shallowThought