Ulli H Ulli H - 6 months ago 105
Swift Question

merge two different images in Swift

I want to merge two

UIImage
in Swift:

enter image description here

and

enter image description here

I tried it with

func maskImage(image: UIImage, withMask maskImage: UIImage) -> UIImage {

let maskRef = maskImage.CGImage

let mask = CGImageMaskCreate(
CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef),
nil,
false)

let masked = CGImageCreateWithMask(image.CGImage, mask)
let maskedImage = UIImage(CGImage: masked!)

// No need to release. Core Foundation objects are automatically memory managed.

return maskedImage

}


and the call

let imageName = data.valueForKey("imagename")!.description
let image = UIImage(named: imageName)
let imageBackground : UIImage = UIImage(named:"background")!
let maskedImage: UIImage = self.maskImage(image!, withMask: imageBackground)

cell.imageButton.setImage(maskedImage, forState: .Normal)


the result is just the image that i get with
let image = UIImage(named: imageName)
, the second image (volleyball)

What´s my error?

Answer

If you don't care about performance you can use Core Image

let volleyballImage = CIImage(image: UIImage(named:"volleyball.png")!)
let otherImage = CIImage(image: UIImage(named:"other.png")!)
let compositeFilter = CIFilter(name: "CIAdditionCompositing")!

compositeFilter.setValue(volleyballImage,
                         forKey: kCIInputImageKey)
compositeFilter.setValue(otherImage,
                         forKey: kCIInputBackgroundImageKey)

if let compositeImage = compositeFilter.outputImage{
    let image = UIImage(CIImage: compositeImage)
    // do something with the "merged" image
}