【发布时间】:2017-08-09 01:17:25
【问题描述】:
从Stackoverflow post 开始,这非常有帮助,我已经能够成功地将文本绘制到全屏图像上(我正在使用预先设置的短字符串标记图像,例如,“垃圾”)。但是,文本没有出现在我想要的位置,它以用户点击的确切点为中心。这是我的代码,基于上面帖子中的一些代码,但针对 Swift3 进行了更新--
func addTextToImage(text: NSString, inImage: UIImage, atPoint:CGPoint) -> UIImage{
// Setup the font specific variables
let textColor: UIColor = UIColor.red
let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 80)!
//Setups up the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
]
// Create bitmap based graphics context
UIGraphicsBeginImageContextWithOptions(inImage.size, false, 0.0)
//Put the image into a rectangle as large as the original image.
inImage.draw(in: CGRect(x:0, y:0, width:inImage.size.width, height: inImage.size.height))
// Create the rectangle where the text will be written
let rect: CGRect = CGRect(x:atPoint.x, y:atPoint.y, width:inImage.size.width, height: inImage.size.height)
// Draft the text in the rectangle
text.draw(in: rect, withAttributes: textFontAttributes)
// Get the image from the graphics context
let newImag = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImag!
}
在上面,atPoint 是用户点击的位置。这是我想要绘制文本的地方。但是,文本总是写在图像的左上角。例如,在所附图像中,我在瀑布的一半处轻敲,因为我希望在此处写入文本字符串“Trash”。但相反,您可以看到它写在左上角。我已经尝试了很多东西,但无法找到解决方案。我很感激任何帮助。 enter image description here
【问题讨论】: