gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:57:08 27 4
gpt4 key购买 nike

我使用此代码将文本从 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com