Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shadow not showing when background color is clear color

Tags:

ios

calayer

I've created an uiview in my xib with background color as clear color. When I apply the shadow on the layer of the view, the shadow is not appearing. But when i set the background color other than clear color, shadow is showing. Please help.

this is my code

self.cView.layer.shadowColor=[UIColor whiteColor].CGColor;
self.cView.layer.shadowOffset=CGSizeZero;
self.cView.layer.shadowRadius=30.0;
self.cView.layer.shadowOpacity=1.0;
self.cView.layer.cornerRadius=10.0;
like image 292
Mukunda Avatar asked Oct 17 '12 05:10

Mukunda


3 Answers

The problem is, that shadow actually takes into account the 'upper' layer. If there's nothing on it there will be no shadow: How Shadows Work

EDIT:

There is this recipe copied from paste bin

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);

But I doubt this will be of any use to you: the result is a view 'painted' with color of a shadow and a shadow around it.

like image 106
Rok Jarc Avatar answered Oct 16 '22 01:10

Rok Jarc


If you specify shadowPath property

shadowView.layer.shadowPath =
  UIBezierPath(
   roundedRect: shadowView.bounds,
   cornerRadius: 10).cgPath

(Or whatever corner radius is desired.)

it will work even with .clear backgroundColor.

Note that you of course have to do this in layoutSubviews of the view in question.

Here's an actual full working example:

import UIKit

@IBDesignable class LonelyShadow: UIView {

    let corner: CGFloat = 20

    override init(frame: CGRect) {
        super.init(frame: frame)
        common()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }

    private func common() {

        backgroundColor = .clear
        clipsToBounds = false

        layer.shadowColor = UIColor.yourColor.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 25)
        layer.shadowOpacity = 0.3
        layer.shadowRadius = 40
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.shadowPath = UIBezierPath(
          roundedRect: bounds, cornerRadius: corner).cgPath
    }
}
like image 18
Senõr Ganso Avatar answered Oct 16 '22 00:10

Senõr Ganso


Equivalent to @Rok Jark's answer in Swift 4:

self.layer.shadowColor = UIColor(white: 0.5, alpha: 1).cgColor
self.layer.shadowRadius = 4.0
self.layer.shadowPath = CGPath.init(rect: CGRect.init(x: 0, y: 0, width: 50, height: 50), transform: nil)
self.layer.shadowOpacity = 1.0;
self.layer.shadowOffset = CGSize(width: 1, height: 1)
like image 3
Newsonic Avatar answered Oct 16 '22 01:10

Newsonic