gpt4 book ai didi

ios - 如何在中心绘制文本到uiimage?

转载 作者:可可西里 更新时间:2023-11-01 00:02:54 26 4
gpt4 key购买 nike

我想将我的文本 Sold Out 设置到 UIimage 的中心。但它不在中心。

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

let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 32)!

let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
] as [String : Any]

image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
// let rect = CGRect(origin: point , size: image.size)
let rect = CGRect(origin: CGPoint(x:(image.size.width/2), y: (image.size.height/2)), size: image.size)

text.draw(in: rect, withAttributes: textFontAttributes)

let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return newImage!
}

调用函数

 imageViewSoldStatus.image = textToImage(drawText: "Sold out", inImage: UIImage(named:"soldout.png")!, atPoint: CGPoint(x: 5.0, y: 5.0))

我花了很长时间来解决这个问题,但我找不到任何解决方案。

红旗我的形象

enter image description here

以上是我得到的画面。下面是我想要实现的设计。

enter image description here

更新

Marie Dm 回答用过!是文字居中而不是图片居中

enter image description here

最佳答案

试试这个:

func textToImage(drawText text: NSString, inImage image: UIImage) -> UIImage? {
//draw image first
UIGraphicsBeginImageContext(image.size)
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))

//text attributes
let font=UIFont(name: "Helvetica-Bold", size: 32)!
let text_style=NSMutableParagraphStyle()
text_style.alignment=NSTextAlignment.center
let text_color=UIColor.white
let attributes=[NSFontAttributeName:font, NSParagraphStyleAttributeName:text_style, NSForegroundColorAttributeName:text_color]

//vertically center (depending on font)
let text_h=font.lineHeight
let text_y=(image.size.height-text_h)/2
let text_rect=CGRect(x: 0, y: text_y, width: image.size.width, height: text_h)
text.draw(in: text_rect.integral, withAttributes: attributes)
let result=UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}

关于ios - 如何在中心绘制文本到uiimage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40626882/

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