Search code examples
swiftxcodestoryboardtransparencyalpha

swift ImageView with low alpha and subImageView transparent showing parent view but with 1 alpha


I'm having trouble setting my subImageViews to show parent ImageView with alpha 1 in their area, but all around I need to have alpha 0.25. Do you have any ideas? I've tried to do it through View, now ImageView but can't find a solution. 16 squares in the middle need to show a clear image, after pressing the button "Start" they would crop their area and send it to other VC. Thanks for help

Screenshot showing simulator with storyboard structure


Solution

  • So I've been playing around a bit and got solution (also thanks to @iOSDev link to article).

    If anyone will need similar kind of thing, here it is :

    @IBOutlet weak var alphaView: UIView!
    @IBOutlet weak var pickedImage: UIImageView!
    @IBOutlet weak var bigStackView: UIStackView!
    
    
    override func viewWillAppear(_ animated: Bool) {
        pickedImage.image = imagePicked
    
    
        // Set white background color with custom alpha
        alphaView.backgroundColor = UIColor(white: 255/255, alpha: 0.85)
    
        // Create the initial layer from the stackView bounds.
        let maskLayer = CAShapeLayer()
        maskLayer.frame = alphaView.bounds
    
        // Create the frame to cover whole stackView
        let rect = CGRect(
            x: bigStackView.frame.minX,
            y: bigStackView.frame.minY,
            width: bigStackView.bounds.width,
            height: bigStackView.bounds.height)
    
        // Create the path
        let path = UIBezierPath(rect: alphaView.bounds)
        maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
    
        // Append the framer to the path so that it is subtracted
        path.append(UIBezierPath(rect: rect))
        maskLayer.path = path.cgPath
    
        // Set the mask of the alphaview
        alphaView.layer.mask = maskLayer
    }
    

    pickedImage is background image view which is covered by aplhaView used only to make it foggy and bigStackView is 16 square in middle to determinate position of wanted square. Might aswell use explicit CGPoint & CGSize Value.

    Screenshot from simulator