Yagiz
Yagiz

Reputation: 1033

Getting masked layer as UIImage on Swift on top of UIImageView

I'm trying to get the UIImage of the mask that I applied to a UIImageView.

I'm adding the mask using UIBezierPath and want the actual masked layer as UIImage, not the whole image. Think of it as a crop feature.

I'm cropping the image using:

func cropImage() {
    shapeLayer.fillColor = UIColor.black.cgColor
    viewSource.imageView.layer.mask = shapeLayer
    viewSource.imageView.layer.masksToBounds = true

    UIGraphicsBeginImageContextWithOptions(viewSource.imageView.bounds.size, false, 1)
    viewSource.imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    self.completionObservable.onNext(newImage)
}

This eventually gives me the masked image on top of the old dimensions (the initial imageView width and height). But I want to have only the masked image, excluding the white background around them.

The screens are as shown:

enter image description here

enter image description here

Upvotes: 1

Views: 1473

Answers (1)

E.Coms
E.Coms

Reputation: 11531

I know what you mean now. Here is the answer, just update the size of imageContext.

          UIGraphicsBeginImageContextWithOptions((shapeLayer.path?.boundingBoxOfPath)!.size, false, 1)

If it's not so simple, can try CIImage pipeline to achieve.

    let context =  CIContext()
    let m1 = newImage?.cgImage
    let m = CIImage.init(cgImage: m1!)
    let bounds = imageView.layer.bounds
    let cgImage =   context.createCGImage(m, from: CGRect.init(x: 0, y: bounds.size.height, width: bounds.size.width, height: bounds.size.height))
    let newUIImage = UIImage.init(cgImage: cgImage!)

You may need to adjust transform.

Upvotes: 1

Related Questions