Search code examples
iosswiftcore-graphics

How to attain opacity in a shape drawn in a layer of UIView that is a subView of a UIImageView?


I have an image presented in a UIImageView which takes up the entire view of the UIViewController. I would like to draw a circle(fill: yellow) in the layer of a subview(UIView) of this UIImageView. My problem is the following, how do I make the opacity of this yellow circle such that it can see through to the background image (e.g opacity 0.2). I have tried the following without success. All I get is a solid yellow circle on top of the background image. I need this yellow circle to be in the layer of the subView as described, rather than in a layer of the UIImageView.

let dotSize: CGFloat = 30
var fourthDotView: UIView?
@IBOutlet weak var imgPreViewOutlet: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    fourthDotView = UIView.init()
    fourthDotView?.frame = CGRect.init(x: fourthOrigin.x, y: fourthOrigin.y, width: dotSize, height: dotSize)

    drawFourthDot()
    imgPreViewOutlet.addSubview(fourthDotView!)

}



// DRAW YELLOW CIRCLE
func drawFourthDot() -> Void {
    let layer = CAShapeLayer.init()
    layer.path = UIBezierPath.init(roundedRect: fourthDotView!.bounds, cornerRadius: 50).cgPath
    layer.fillColor = UIColor.init(red: 255, green: 255, blue: 0, alpha: 0.2).cgColor
    fourthDotView?.layer.addSublayer(layer)
}

Solution

  • For setting the opacity, you should use the opacity property.

    layer.opacity = 0.20