开启此Stackoverflow post,这非常有帮助,我已经能够成功地将文本绘制成全屏图像,屏幕图像(我标记的图像与前罐头,短字符串,例如,“回收站”)。但是,该文本并未出现在我想要的位置,而是以用户点击的确切位置为中心。这里是我的代码的基础上,从上面发布一些代码,但更新的Swift3 -Swift 3 - NSString.draw(in:rect,withAttributes :) - 未在预期点绘制文字
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是用户的敲击的位置。这是我想要绘制文本的地方。但是,文本总是写入图像的左上角。例如,附加的图像中,我已经利用中途而下的瀑布,因为这是我想要的写入文本字符串“回收站”。但是,您可以看到它在左上角写着。我尝试了一堆东西,但无法获得解决方案。我感谢任何帮助。 enter image description here
TrashShouldBeInMiddleOfWaterfallButIsNot
谢谢你,谢谢你,谢谢你!作品! – Yorma