How to set a proper location for CIAttributedTextImageGenerator?

567 views Asked by At

I use "CIAttributedTextImageGenerator" to generate a CIImage from text and then I overlay it on my edited image with "CISourceAtopCompositing" :

    // Text to image
    let font = UIFont.systemFont(ofSize: 78)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    paragraphStyle.firstLineHeadIndent = 5.0
    
    let shadow = NSShadow()
    shadow.shadowColor = UIColor.red
    shadow.shadowBlurRadius = 5

    let attributes: [NSAttributedString.Key: Any] = [
        .font: font,
        .foregroundColor: UIColor.blue,
        .paragraphStyle: paragraphStyle,
        .shadow: shadow
    ]

    let attributedQuote = NSAttributedString(string: "General Kenobi", attributes: attributes)
    let textGenerationFilter = CIFilter(name: "CIAttributedTextImageGenerator")!
    textGenerationFilter.setValue(attributedQuote, forKey: "inputText")
    textGenerationFilter.setValue(NSNumber(value: Double(inputSizeFactor)), forKey: "inputScaleFactor")
    let textImage = textGenerationFilter.outputImage!.oriented(.right)
    
    
    finalImage = textImage
        .applyingFilter("CISourceAtopCompositing", parameters: [ kCIInputBackgroundImageKey: finalImage])

However, the text image is always in the right bottom corner of my edited image:

enter image description here

How can I set it a custom location? For example, if I want it to be in the bottom right corner, or in the center of the edited image?

1

There are 1 answers

0
Frank Rupprecht On BEST ANSWER

You can apply transformations to the image before you composite it over the background:

let transformedText = textImage.transformed(by: CGAffineTransform(translationX: 200, y: 300)

I'm afraid you have to calculate the exact position for centering the image yourself. There's no built-in way to center one image ontop another.