gpt4 book ai didi

swift - 如何让文字出现在图片的中央?

转载 作者:行者123 更新时间:2023-11-28 09:59:48 26 4
gpt4 key购买 nike

我想在图像上添加文本,我可以按照下面的代码所示进行操作。

func textToImage(drawText: NSString, inImage: UIImage, atPoint:CGPoint)->UIImage{

// Setup the font specific variables
var textColor: UIColor = UIColor.redColor()
var textFont: UIFont = UIFont(name: "AmericanTypewriter", size: 75)!
let textStyle = NSTextEffectLetterpressStyle

//Setup the image context using the passed image.
UIGraphicsBeginImageContext(inImage.size)

let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
NSTextEffectAttributeName : textStyle
]

inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))

var rect: CGRect = CGRectMake(atPoint.x, atPoint.y, inImage.size.width, inImage.size.height)

drawText.drawInRect(rect, withAttributes: textFontAttributes)

var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()
return newImage
}

我调用了这个函数,如下所示

let newImage : UIImage = textToImage(textToAdd!, inImage: imageToSave, atPoint:CGPoint(x: 20, y: 20)) //For now text is displaying at the top in left end for point(x:20 ,y:20)

但问题是,文本被用户获取了。他们可以给出单个单词或大句子。因此,如果他们只给出一个词,它应该出现在图像的顶部和中间,或者从左到右出现在顶部。更像是,我想将文本对齐方式设置为居中。为此,我应该更改上面给出的 CGPoint。但我不知道如何更改它,以便它在所有情况下看起来都不错。请帮助我如何实现这一目标。

最佳答案

您可以像这样将文本居中放置在图像顶部附近:

    func textToImage(drawText: NSString, inImage: UIImage, atPoint:CGPoint)->UIImage{

// Setup the font specific variables
var textColor: UIColor = UIColor.redColor()
var textFont: UIFont = UIFont(name: "AmericanTypewriter", size: 75)!
let textStyle = NSTextEffectLetterpressStyle

//Setup the image context using the passed image.
UIGraphicsBeginImageContext(inImage.size)

let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
NSTextEffectAttributeName : textStyle
]

inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))

let textSize = drawText.sizeWithAttributes(textFontAttributes)
let textRect = CGRectMake(inImage.size.width / 2 - textSize.width / 2, 0,
inImage.size.width / 2 + textSize.width / 2, inImage.size.height - textSize.height)
drawText.drawInRect(textRect, withAttributes: textFontAttributes)

var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()
return newImage
}

关于swift - 如何让文字出现在图片的中央?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30629118/

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