I have a custom view with corner radius and shadow, and I'm trying to add an image inside it. The image should be inside the rounded area. But I'm getting a black area in the view, where the image should be, (or the image as an square, without round corners, on my last attempt). How can I add this image?
The wrong result I'm getting:
My code:
import Foundation
import UIKit
@IBDesignable
class RoundedSquareView: UIView {
var shadowLayer: CAShapeLayer!
@IBInspectable var image: UIImage! = UIImage()
override func layoutSubviews() {
super.layoutSubviews()
if shadowLayer == nil {
shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 14).cgPath
shadowLayer.fillColor = UIColor.white.cgColor
shadowLayer.shadowColor = UIColor.darkGray.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 0, height: 10.0)
shadowLayer.shadowOpacity = 0.3
shadowLayer.shadowRadius = 10
layer.insertSublayer(shadowLayer, at: 0)
}
let imgLayer = CAShapeLayer()
let myImage = image.cgImage
imgLayer.frame = bounds
imgLayer.masksToBounds = true
imgLayer.contents = myImage
imgLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 14).cgPath
imgLayer.cornerRadius = 14
layer.addSublayer(imgLayer)
}
}
EDIT:
The expected result: