【发布时间】:2017-06-01 11:55:25
【问题描述】:
我想在 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!
}
}
问题是如果文本太长或太大,它会超出屏幕。我需要更改原点以将文本从右向左写入,这样它只会在左侧占用空间,而不是在屏幕右侧占用空间。我怎么能这样做?
【问题讨论】:
-
添加标签作为子视图并创建图像视图的“截图”可能更容易。 Here is how.