I am writing in Swift trying to mask an image using UIImage and CALayer. The problem is that the mask is scaled and shifted when applied to the image. I created my UIImageViewer using Interface Builder and I installed it in Aspect Fit. I would like to mask images of arbitrary size. I am creating a mask image of the same size as the image. This is a requirement because later I want to programmatically add elements to the mask in the mask, and it should cover the masked image. Here is my code:
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
var img = UIImage(named: "flowers.png")
var maskImageSize = CGSizeMake(img!.size.width, img!.size.height)
UIGraphicsBeginImageContextWithOptions(maskImageSize, false, 0.0)
var color = UIColor(white: 1.0, alpha: 0.0)
color.setFill()
var rect = CGRectMake(0, 0, img!.size.width, img!.size.height)
UIRectFill(rect)
color = UIColor(white: 0.0, alpha: 1.0)
color.setFill()
rect = CGRectMake((img!.size.width/2)-50, (img!.size.height/2)-50, 100, 100)
UIRectFill(rect)
var maskImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var maskLayer = CALayer()
maskLayer.frame = self.imageView.layer.bounds
maskLayer.contents = maskImage.CGImage
maskLayer.contentsGravity = kCAGravityCenter
self.imageView.image = img
self.imageView.layer.mask = maskLayer;
self.imageView.layer.masksToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I need to know how to align the image mask with the original image. Thank you for your help!
I have good screenshots, but Stackoverflow does not allow me to publish them because I do not have enough reputation!