Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
Ulli H Avatar asked Oct 29 '25 06:10

Ulli H


2 Answers

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
}
like image 170
beyowulf Avatar answered Oct 31 '25 00:10

beyowulf


You can do it in few lines:

var bottomImage:UIImage = UIImage(named: "imageName")!
var topImage:UIImage = UIImage(named:"background")!
// Change here the new image size if you want
var newSize = CGSizeMake(bottomImage.size.width, bottomImage.size.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, bottomImage.scale)
bottomImage.drawInRect(CGRectMake(0,0,newSize.width,newSize.height))
topImage.drawInRect(CGRectMake(0,0,newSize.width,newSize.height), blendMode:CGBlendMode.Normal, alpha:1.0)
var newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
like image 34
Alessandro Ornano Avatar answered Oct 30 '25 23:10

Alessandro Ornano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!