crista inlika2 crista inlika2 - 20 days ago 8
iOS Question

how to draw text in center to uiimage?

I want to set my text Sold Out to the center in UIimage. but it not in center .

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!
}


caller function

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


I have spent of very long time to solve this problem but I could not find any solution.

Red flag my image

enter image description here

above is the screen I obtained. below is the design that I want to achieve.

enter image description here

update

Marie Dm answerd used! it is text align center but not image center

enter image description here

Answer

Try this:

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

    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]
    let text_rect=CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    text.draw(in: text_rect.integral, withAttributes: attributes)
    let result=UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}