如何在CIImage中添加文本?

5
我正在使用Photos框架,并创建了一个应用程序,将在图片上应用过滤器。现在,我想在图像上添加文本而不是应用过滤器。此API为我提供了一个CIImage,我可以使用它来创建输出CIImage。我只是不知道如何将文本添加到CIImage的特定位置。如果我没错的话,由于性能下降,不建议将其转换为CGImage然后添加文本。
如何使用现有的CIImage在特定位置输出完全相同的CIImage(保留原始图像质量)并在顶部放置文本?
//Get full image
let url = contentEditingInput.fullSizeImageURL
let orientation = contentEditingInput.fullSizeImageOrientation
var inputImage = CIImage(contentsOfURL: url)
inputImage = inputImage.imageByApplyingOrientation(orientation)

//TODO: REPLACE WITH TEXT OVERLAY
/*//Add filter
let filterName = "CISepiaTone"
let filter = CIFilter(name: filterName)
filter.setDefaults()
filter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage: CIImage = filter.outputImage*/

//Create editing output
let jpegData: NSData = self.jpegRepresentationOfImage(outputImage)
let adjustmentData = PHAdjustmentData(formatIdentifier: AdjustmentFormatIdentifier, formatVersion: "1.0", data: filterName.dataUsingEncoding(NSUTF8StringEncoding))

let contentEditingOutput = PHContentEditingOutput(contentEditingInput: contentEditingInput)
jpegData.writeToURL(contentEditingOutput.renderedContentURL, atomically: true)
contentEditingOutput.adjustmentData = adjustmentData

PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
    let request = PHAssetChangeRequest(forAsset: asset)
request.contentEditingOutput = contentEditingOutput
}, completionHandler: { (success: Bool, error: NSError!) -> Void in
    if !success {
        NSLog("Error saving image: %@", error)
    }
})
2个回答

4

您可以将文本以灰度形式绘制到一个单独的CGImage中,通过[+CIImage imageWithCGImage:]CGImage转换为CIImage,然后将其用作蒙版,将其和原始的CIImage发送到CIBlendWithMask过滤器。


很棒。正是我想要的! - Jordan H
2
有 Swift 的示例吗? - user924

2

去年推出了一个名为 CIFilter 的新功能,其中包括一个叫做 CIAttributedTextImageGenerator 的工具。以下是我使用该工具编写的实用类方法示例:

+ (CIImage *)imageWithText:(NSString *)message color:(CIColor *)color scaleFactor:(CGFloat)scaleFactor
{
    NSDictionary *attributes = @{
        NSForegroundColorAttributeName : CFBridgingRelease(CGColorCreateSRGB(color.red, color.green, color.blue, color.alpha)),
    };
    NSAttributedString *text = [[NSAttributedString alloc] initWithString:message attributes:attributes];

    CIFilter<CIAttributedTextImageGenerator> *filter = [CIFilter attributedTextImageGeneratorFilter];
    filter.text = text;
    filter.scaleFactor = scaleFactor;

    CIImage *result = filter.outputImage;
    return result;
}

很不幸,似乎存在一个错误,不允许您为此筛选器的后续调用选择新颜色。也就是说,一旦您首次渲染此筛选器,每个后续渲染都将产生与第一次渲染相同颜色的文本,而不管传递的颜色如何。

无论如何,这将产生一个CIImage,然后您可以像这样覆盖到您的inputImage上:

CIImage *textImage = [YourUtilityClass imageWithText:@"Some text" color:[CIColor whiteColor] scaleFactor:1.0];
CIImage *outputImage = [textImage imageByCompositingOverImage:inputImage];

我最近没有太多使用Swift的经验,但是希望这段Objective-C代码足够简单明了,让您能够理解。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接