2017-05-15 44 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