我使用此代码将textview中的文本添加到Image
func textToImage(drawText: NSString, inImage: UIImage, atPoint: CGPoint) -> UIImage{
// Setup the font specific variables
var textColor = UIColor.whiteColor()
var textFont = UIFont(name: "Helvetica Bold", size: 12)!
// Setup the image context using the passed image
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(inImage.size, false, scale)
// Setup the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
]
// Put the image into a rectangle as large as the original image
inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))
// Create a point within the space that is as bit as the image
var rect = CGRectMake(atPoint.x, atPoint.y, inImage.size.width, inImage.size.height)
// Draw the text into an image
drawText.drawInRect(rect, withAttributes: textFontAttributes)
// Create a new image out of the images we have created
var newImage = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//Pass the image back up to the caller
return newImage
}
我从服务器下载图片,并为此添加文字。我在添加文本之前已经调整了图像大小以适合我正在使用的设备,在这种情况下是Iphone 6s,375 * 667
当我将图片中红色的textView中的文本添加到我的图像时,它不在正确的位置。它总是无缘无故地向右推。
答案 0 :(得分:0)
想象一下你有一个正方形。如果将X和Y都设置为0,则不会将正方形的中间放置到x:0和y:0。它会将该正方形的左上角放置到该坐标。您的问题是,当您调用函数时,它会将文本的左上角放在您点击的位置。你必须减去X的文本宽度的一半和Y的文本高度的一半。它应该看起来像这样:
func textToImage(drawText: "Hello, inImage: ***YOUR_IMAGE***, atPoint: CGPoint(x: point.x - (text.frame.width / 2), y: point.y - (text.frame.height / 2))