2017-05-15 45 views
-2

如何使用Objective-C在iOS中实现输出.. Image-1 + Image-2 = Image-3?使用Objective C进行图像混合

Image-1

Image-2

Image -3

如何可以使用Objective-C实现在IOS输出.. 图片-1 +图像2 =图像-3

+0

试试这个http://stackoverflow.com/questions/37495730/how-to-blend-two-images –

+0

http://stackoverflow.com/questions/18273271/merge-two-image-on-to-一个图像编程在iphone?rq = 1检查这个,但它垂直组合2个图像,你可以更新矩形。这可能会帮助你! –

+0

好吧,似乎有人对这个问题投了弃权票。你能否解释给出投票的理由?我真的很想知道这一点。 – emraz

回答

3
//: Playground - noun: a place where people can play 

import UIKit 
import CoreImage 

func aspectFill(from: CGRect, to: CGRect) -> CGAffineTransform { 
    let horizontalRatio = to.width/from .width 
    let verticalRatio = to.height/from.height 
    let scale = max(horizontalRatio, verticalRatio) 
    let translationX = horizontalRatio < verticalRatio ? (to.width - from.width * scale) * 0.5 : 0 
    let translationY = horizontalRatio > verticalRatio ? (to.height - from.height * scale) * 0.5 : 0 
    return CGAffineTransform(scaleX: scale, y: scale).translatedBy(x: translationX, y: translationY) 
} 

func filter(image: UIImage, texture: UIImage) -> UIImage? { 
    guard let imageCI = CIImage(image: image), 
     let textureCI = CIImage(image: texture) 
     else { 
      return nil 
    } 

    let scaleFillTextureCI = textureCI.applying(aspectFill(from: textureCI.extent, to: imageCI.extent)) 
    let crop = CIFilter(name: "CICrop")! 
    crop.setValue(scaleFillTextureCI, forKey: "inputImage") 
    crop.setValue(imageCI.extent, forKey: "inputRectangle") 

    let alpha = CIFilter(name: "CIConstantColorGenerator")! 
    alpha.setValue(CIColor.init(red: 0, green: 0, blue: 0, alpha: 0.7), forKey: "inputColor") 

    let mix = CIFilter(name: "CIBlendWithAlphaMask")! 
    mix.setValue(imageCI, forKey: "inputImage") 
    mix.setValue(crop.outputImage, forKey: "inputBackgroundImage") 
    mix.setValue(alpha.outputImage, forKey: "inputMaskImage") 

    let blend = CIFilter(name: "CIBlendWithMask")! 
    blend.setValue(imageCI, forKey: "inputImage") 
    blend.setValue(mix.outputImage, forKey: "inputBackgroundImage") 
    blend.setValue(imageCI, forKey: "inputMaskImage") 

    let context = CIContext(options: nil) 
    guard let ciImage = blend.outputImage, 
     let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { 
      return nil 
    } 

    return UIImage(cgImage: cgImage) 
} 

let image = #imageLiteral(resourceName: "image.jpg") 
let texture = #imageLiteral(resourceName: "texture.jpg") 
let output = filter(image: image, texture: texture)] 

我在Swift解决方案,因为我不熟悉Objective-C语法,但我认为你可以转化为Objective-C容易。 您可以使用CoreImage来达到效果。这里来自Xcode Playground的结果。 Screenshot