1 year ago

#321964

test-img

SmartTree

CIAttributedTextImageGenerator filter - text doesn't fit (NSAttributedString)

I use a Core Image filter CIAttributedTextImageGenerator to generate text as a CIImage. However, sometimes the text just doesn't fit into the resulted CIImage as you can see at the picture:

enter image description here

I tried to play with different key-values of NSAttributedString to make some padding around text but with no success:

func generateImageFromText(_ text: String, style: TextStyle) -> CIImage? {
    
    let font = UIFont.init(name: style.fontName, size: style.fontSize)!
    
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = style.textAlignment
    paragraphStyle.headIndent = 5.0
    paragraphStyle.tailIndent = -5.0
    paragraphStyle.firstLineHeadIndent = 0
    
    let shadow = NSShadow()

    if let shadowStyle = style.shadowStyle {
        shadow.shadowColor = shadowStyle.color
        shadow.shadowOffset = shadowStyle.offset
        shadow.shadowBlurRadius = shadowStyle.blurRadius
    }
        
    var strokeColor = UIColor.clear
    var strokeWidth: CGFloat = 0.0
    
    if let strokeStyle = style.strokeStyle {
        strokeColor = strokeStyle.color
        strokeWidth = strokeStyle.width
    }
    
    let attributes: [NSAttributedString.Key: Any] = [
        .baselineOffset: 50,
        .font: font,
        .foregroundColor: style.color,
        .paragraphStyle: paragraphStyle,
        .shadow: shadow,
        .strokeColor: strokeColor,
        .strokeWidth: strokeWidth
    ]
    
    let attributedQuote = NSAttributedString(string: text, attributes: attributes)
    
    let textGenerationFilter = CIFilter(name: "CIAttributedTextImageGenerator")!
    textGenerationFilter.setValue(attributedQuote, forKey: "inputText")
    textGenerationFilter.setValue(NSNumber(value: Double(1.0)), forKey: "inputScaleFactor")
    
    guard let textImage = textGenerationFilter.outputImage else {
        return nil
    }
    
    return textImage
}

Maybe there are some values of NSAttributedString that I miss which can help to fit in the text?

swift

nsattributedstring

core-image

cifilter

0 Answers

Your Answer

Accepted video resources