如何将文本添加到CIImage?
问题描述:
我正在使用Photos框架,并且已经创建了一个将过滤器应用于图像的应用程序。现在不用应用滤镜,我想在图像上添加文本。该API为我提供了一个CIImage
,我可以使用它来创建输出CIImage
。我只是不知道如何在特定位置添加文字到CIImage
。如果我是正确的,建议不要将其转换为CGImage
,然后由于性能下降而添加文本。如何将文本添加到CIImage?
如何使用现有的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)
}
})
答
你可以绘制灰度文本到一个单独的CGImage
,转换CGImage
成CIImage
(通过[+CIImage imageWithCGImage:]
),然后使用它作为一个面具,它和原来的CIImage
发送到CIBlendWithMask
过滤器。
美丽。正是我在找的! – Joey 2014-09-02 05:04:06
你能用小代码示例显示这个吗? – 2016-05-18 14:51:41
swift中的任何示例? – user924 2018-03-01 14:00:45