Iam trying to apply shadow to tableView
cell
, which is rounded.
So the cell view's hierarchy is:
-TableView
-Cell //height 85
-ContentView //height 85
-View //height 85
-RoundedView //height 65
And this is how I am applying the shadow:
extension UIView{
func dropShadow(x: CGFloat, y: CGFloat, cornerRadius: CGFloat, shadowRadius: CGFloat, color: CGColor, opacity: Float) {
self.layer.cornerRadius = cornerRadius //Give the view corner radius
self.layer.shadowColor = color //Shadow color
self.layer.shadowOffset = CGSize(width: x, height: y)//Offset like in Sketch X and Y
self.layer.shadowRadius = shadowRadius //It should be the blur in Sketch
self.layer.shadowOpacity = 1.0
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
}
}
These are the Sketch properties:
I have even exported the shadow color from Sketch:
cellShadow = UIColor(hue: 0.643, saturation: 0.061, brightness: 0.906, alpha: 0.5)//Alpha 0.5
And this is the output on iPhone:
And this is the design in Sketch:
Why the shadow cuts on iPhone and why the color is different a little(I am using color picker to see if it matches but it is not matching)? What I am doing wrong, can anybody tell me?
The first thing to notice is that you have set the color to...
UIColor(hue: 0.643, saturation: 0.061, brightness: 0.906, alpha: 0.5)
This already includes the opacity from Sketch as Sketch defines the shadow opacity in the color.
Then you are doing this...
layer.shadowOpacity = 0.5
Which then takes that color (with 50% opacity) and applies a 50% alpha to it. So now you effectively have a 25% opacity.
In defining the color set the alpha to 1. Not 0.5. That will darken the color.
You haven't shown how your other shadow properties are set up in Sketch so thats all I can advise for now.
EDIT
OK...
The colours look a lot better now.
The reason for the cut off is that your shadow radius is HUGE! (Seriously, does it need to be that big? Normally 4 or 6 will cut it. 20 is overkill.)
The reason this is happening is that the distance between the "content view" (the one with the shadow on it) and the edge of the cell is not enough to accommodate the full shadow.
You have an offset of 5 vertically and a radius of 20 so that means you'll need at least a distance of 25 from the bottom of the "content view" to the edge of the cell to fully display the shadow. (15 at the top... 20 - 5).
Another option is to disable clipsToBounds
on the cell... cell.clipsToBounds = false
. The downside to this is that your shadows may collide causing darker spots where the overlap.
TBH though, just reduce the radius and the problem disappears :D