How to add shadow to transparent UIView?

How can I reproduce this shading? My problem is that if I use high alpha color or clearColor, there is no shadow for the shadow, if I use low alpha color, I do not see the shadow under the plate. As the volume level changes (the colorful part), the shadow also moves, so this is not pure Photoshop.

enter image description here

+6
source share
4 answers

try something using the points of your presentation. it may end with something

    view.layer.shadowColor = [UIColor colorWithWhite:.5 alpha:1].CGColor;
    view.layer.shadowRadius = 4.0f;
    view.layer.shadowPath = CGPathCreateWithRect(CGRectMake(0, 0, 50, 50), NULL);
    view.layer.shadowOpacity = 1.0f;
    view.layer.shadowOffset = CGSizeMake(1, 1);

it leaks, by the way, should CGPathRelease (rect) at the end sorry.

+9
source

After searching and not finding the answer to this question, I wrote the following extension in Swift 5:

extension UIView {
    func makeClearViewWithShadow(
        cornderRadius: CGFloat,
        shadowColor: CGColor,
        shadowOpacity: Float,
        shadowRadius: CGFloat) {

        self.frame = self.frame.insetBy(dx: -shadowRadius * 2,
                                        dy: -shadowRadius * 2)
        self.backgroundColor = .clear
        let shadowView = UIView(frame: CGRect(
            x: shadowRadius * 2,
            y: shadowRadius * 2,
            width: self.frame.width - shadowRadius * 4,
            height: self.frame.height - shadowRadius * 4))
        shadowView.backgroundColor = .black
        shadowView.layer.cornerRadius = cornderRadius
        shadowView.layer.borderWidth = 1.0
        shadowView.layer.borderColor = UIColor.clear.cgColor

        shadowView.layer.shadowColor = shadowColor
        shadowView.layer.shadowOpacity = shadowOpacity
        shadowView.layer.shadowRadius = shadowRadius
        shadowView.layer.masksToBounds = false
        self.addSubview(shadowView)

        let p:CGMutablePath = CGMutablePath()
        p.addRect(self.bounds)
        p.addPath(UIBezierPath(roundedRect: shadowView.frame, cornerRadius: shadowView.layer.cornerRadius).cgPath)

        let s = CAShapeLayer()
        s.path = p
        s.fillRule = CAShapeLayerFillRule.evenOdd

       self.layer.mask = s
    }
}

Usage example:

myView.makeClearViewWithShadow(cornderRadius: 20, shadowColor: UIColor.black.cgColor, shadowOpacity: 0.5, shadowRadius: 30)
+3

: - , -

, ,

0

I used UIImageView to provide shadow. I created an image 1 pixel wide, 12 pixels high. The image was black, but alpha ranged from 0.5 at the top to 0.0 at the bottom, for example. RGBA 1.0,1.0,1.0,0.5 → 1.0,1.0,1.0,0.0 - Then I placed the UIImageView just below the view requiring a shadow, and stretched it horizontally across the width of the view. I also used this when I needed to change the shadow intensity while scrolling down the scrollbar by changing the value of UIImageView.alpha

0
source

All Articles