如何为 CIAttributedTextImageGenerator 设置合适的位置?
How to set a proper location for CIAttributedTextImageGenerator?
我使用 "CIAttributedTextImageGenerator"
从文本生成 CIImage
,然后用 "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])
但是,文本图像总是在我编辑的图像的右下角:
如何将其设置为自定义位置?比如我想让它在编辑后的图片的右下角,或者居中?
您可以在将图像合成到背景之前对图像应用变换:
let transformedText = textImage.transformed(by: CGAffineTransform(translationX: 200, y: 300)
恐怕您必须自己计算图像居中的确切位置。无法 built-in 将一张图片置于另一张图片的中央。
我使用 "CIAttributedTextImageGenerator"
从文本生成 CIImage
,然后用 "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])
但是,文本图像总是在我编辑的图像的右下角:
如何将其设置为自定义位置?比如我想让它在编辑后的图片的右下角,或者居中?
您可以在将图像合成到背景之前对图像应用变换:
let transformedText = textImage.transformed(by: CGAffineTransform(translationX: 200, y: 300)
恐怕您必须自己计算图像居中的确切位置。无法 built-in 将一张图片置于另一张图片的中央。