swift - Swift 添加文本到图像不在正确的位置

标签 swift image text

我使用此代码将文本从 TextView 添加到图像

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 中的文本添加到我的图像时,它的位置不正确。它总是无缘无故地被推到右边。

有人知道这个问题吗? 非常感谢 !!! When I type text view

The result

最佳答案

想象你有一个正方形。如果将 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))

关于swift - Swift 添加文本到图像不在正确的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40299146/

相关文章:

ios - 图像选择器显示多个图像,如拼贴画,没有内存问题

java - 通过shell脚本在Java程序中从计算机读取图像文件

c# - 在 C# 中从 PDF 中提取文本

string - R 文本挖掘 - 将段落一个接一个地组合在一起,而不会混淆句子

swift - 无法将类型 'String' 的值转换为预期的参数类型 'TimeInterval'(又名 'Double')

swift - Firebase Firestore 查询未执行

swift - Swift 中 auto 和 escaping 闭包的区别和目的是什么?

ios - 模式匹配和类型转换之间的区别

iphone - 适用于 iPhone 的星巴克/iPod 景观式图像浏览器

c# - 使用 LINQ 逐字读取文本文件