I'm just trying to add a shadow to the image, which is not just rectangular, I'd like to apply the same mask effect as image has. On stack overflow I've found the same question, but the answer is suggested on objective-c language -
Now, with just the mask:
and, with the mask AND shadow:
and finally, without the red border showing the frame:
Here's an example view controller:
class MaskShadowViewController: UIViewController {
let testView = ShadowMaskImageView()
override func viewDidLoad() {
super.viewDidLoad()
// make sure we can load the image
guard let img = UIImage(named: "sample") else {
fatalError("Could not load sample image!!!")
}
// set the image
testView.image = img
// add testView and set its height equal to the ratio of the original image
testView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(testView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
testView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
testView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
testView.heightAnchor.constraint(equalTo: testView.widthAnchor, multiplier: img.size.height / img.size.width),
testView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
])
// un-comment the following if we want to see the frame of our custom view
//let frameView = UIView()
//frameView.translatesAutoresizingMaskIntoConstraints = false
//view.addSubview(frameView)
//NSLayoutConstraint.activate([
// frameView.topAnchor.constraint(equalTo: testView.topAnchor, constant: 0.0),
// frameView.leadingAnchor.constraint(equalTo: testView.leadingAnchor, constant: 0.0),
// frameView.trailingAnchor.constraint(equalTo: testView.trailingAnchor, constant: 0.0),
// frameView.bottomAnchor.constraint(equalTo: testView.bottomAnchor, constant: 0.0),
//])
//
//frameView.layer.borderWidth = 1
//frameView.layer.borderColor = UIColor.red.cgColor
}
}