CIAttributedTextImageGenerator 过滤器 - 文本不适合 (NSAttributedString)

问题描述 投票:0回答:1

我使用

Core Image
过滤器
CIAttributedTextImageGenerator
来生成文本作为
CIImage
。然而,有时文本不适合结果
CIImage
,如图所示:

enter image description here

我尝试使用

NSAttributedString
的不同键值在文本周围进行一些填充,但没有成功:

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
}

也许我错过了一些

NSAttributedString
的值,这可以帮助适应文本?

swift nsattributedstring core-image cifilter
1个回答
0
投票

将 inputPadding 设置为等于描边宽度

textGenerationFilter.setValue(strokeWidth, forKey: "inputPadding")

它将修正你的答案。

© www.soinside.com 2019 - 2024. All rights reserved.