I have to create a custom UIView
that will have round corners, a border, a shadow and its drawRect()
method is overridden to provide custom drawing code with which several straight lines are drawn into the view (I need to use a fast, lightweight approach here since many of these views may be rendered).
The problem I'm currently facing is that the shadow doesn't apply anymore to the round corners as soon as I override drawRect()
in the view class (even without any custom code yet in it). See the attached image for the difference:
In the view controller I'm using the following code:
view.layer.cornerRadius = 10;
view.layer.masksToBounds = true;
view.layer.borderColor = UIColor.grayColor().CGColor;
view.layer.borderWidth = 0.5;
view.layer.contentsScale = UIScreen.mainScreen().scale;
view.layer.shadowColor = UIColor.blackColor().CGColor;
view.layer.shadowOffset = CGSizeZero;
view.layer.shadowRadius = 5.0;
view.layer.shadowOpacity = 0.5;
view.layer.masksToBounds = false;
view.clipsToBounds = false;
In the overridden drawContext()
I would use something like:
var context:CGContext = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor);
// Draw them with a 2.0 stroke width so they are a bit more visible.
CGContextSetLineWidth(context, 2.0);
CGContextMoveToPoint(context, 0.0, 0.0); //start at this point
CGContextAddLineToPoint(context, 20.0, 20.0); //draw to this point
CGContextStrokePath(context);
But as said above, the shadow problem occurs even without this code added.
Is there any other/better way to draw lightweight elements onto a view other than this approach that is compatible with round corners and shadows? I don't want to add any unnecessary extra views or image contexts to the view since these need to be light and performant.
I find the following link helpful to understand setting the dropshadow:
How to add a shadow to a UIView
To set the round corner for UIVIEW just set the
layer.cornerRadius
value in interface builder, Please check screenshot.you can use this function for your all views.
In Swift. What did work for me was adding:
So, the full code is:
The solution seems much easier than the problem might suggest. I had this with one of my views and used the core part of @Hodit's answer to get it to work. This is all you need actually:
Note that this doesn't clip subviews. Anything positioned at 0,0 in the view will overlap the visible top left rounded corner.
Here's the swift3 version of Hodit's answer, I had to use it and found it over here and did general corrections for XCode 8. Works like charm!
This is an older question, but I would have just done everything in your custom draw method like below.
I usually will do this if I know I want to apply a drop shadow to my rounded view (which of course means I don't want to use
masksToBounds
)You also don't have to add an extra "shadow view" to the hierarchy.