How create a shadow of three sides in UIView (Right, Left, Bottom) in swift 4? - uiview

I am tried to create a shadow of UIView(Right, left, bottom), does not create an exact shadow. How can I create a shadow of UIView(like below image)? Please help me!
Shadow image

You can add drop shadow to your view using UIBezierPath like this:
extension UIVIew{
func applyDropShadow(scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.shadowRadius = 1
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
adjust the shadowOffset to get the design shadow position.

Related

How to create a solid rectangle border around the circle in UICollectionView Swift4+

I have tried the following but only creates a border around the circle but not a separate rectangle border.
as shown here
cell.layer.borderWidth = 1.0
cell.layer.borderColor = UIColor.black.cgColor
I want to create a rectangle border as shown here
Instead of
cell.layer.borderWidth = 1.0
cell.layer.cornerRadius = 10
cell.layer.borderColor = UIColor.black.cgColor
Have you tried?
cell.layer.borderWidth = 1.0
cell.layer.borderColor = UIColor.black.cgColor
I'm not sure if it'll work for you, but you can try to add an additional layer like that:
var rect = UIView()
var circle: CALayer?
override func loadView() {
// create view with border
rect.frame = CGRect(x: 50, y: 50, width: 300, height: 200)
rect.layer.borderColor = UIColor.black.cgColor
rect.layer.backgroundColor = UIColor.clear.cgColor
rect.layer.borderWidth = 2
// add circle layer
let circle = CALayer()
circle = UIColor.red.cgColor
// add circle layer on view with drawn border
rect.layer.addSublayer(circle)
view.addSubview(rect)
circle = circle
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// layout circle on your view
let radius = min(rect.frame.width, rect.frame.height) * 0.5
circle?.frame = CGRect(x: rect.bounds.width / 2 - radius / 2, y: rect.bounds.height / 2 - radius / 2, width: radius, height: radius)
circle?.cornerRadius = radius / 2
}
But probably that's not the best option, maybe someone gives you better solution.
If it doesn't work for you, please, give more details of you problem.

Shadows masks to bounds only on the left and upper side. What causes this?

I'm trying to achieve a feature that allows adding a shadow to a transparent button. For this, I'm creating a layer that masks the shadows inside the view. However, my shadows are clipped on the left and upper sides but not clipped on the right and lower sides.
Here is how it looks (This is not a transparent button but they're also working fine except the shadow being clipped like this.):
And here is my code for achieving this:
private func applyShadow() {
layer.masksToBounds = false
if shouldApplyShadow && shadowLayer == nil {
shadowLayer = CAShapeLayer()
let shapePath = CGPath(roundedRect: bounds, cornerWidth: cornerRadi, cornerHeight: cornerRadi, transform: nil)
shadowLayer.path = shapePath
shadowLayer.fillColor = backgroundColor?.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowRadius = shadowRadius ?? 8
shadowLayer.shadowColor = (shadowColor ?? .black).cgColor
shadowLayer.shadowOffset = shadowOffset ?? CGSize(width: 0, height: 0)
shadowLayer.shadowOpacity = shadowOpacity ?? 0.8
layer.insertSublayer(shadowLayer!, at: 0)
/// If there's background color, there is no need to mask inner shadows.
if backgroundColor != .none && !(innerShadows ?? false) {
let maskLayer = CAShapeLayer()
maskLayer.path = { () -> UIBezierPath in
let path = UIBezierPath()
path.append(UIBezierPath(cgPath: shapePath))
path.append(UIBezierPath(rect: UIScreen.main.bounds))
path.usesEvenOddFillRule = true
return path
}().cgPath
maskLayer.fillRule = .evenOdd
shadowLayer.mask = maskLayer
}
}
}
I think that's something related to the Even-Odd Fill Rule algorithm, I'm not sure. But how can I overcome this clipping problem?
Thanks in advance.
EDIT:
This is what a transparent button with borders and text on it looks when shadow applied.. Which I don't want.
What it should look like this. No shadows inside but also a clear background color. (Except the clipped top and left sides):
I think a couple issues...
You are appending UIBezierPath(rect: UIScreen.main.bounds) to your path, but that puts the top-left corner at the top-left corner of the layer... which "clips" the top-left shadow.
If you DO have a background color, you'll need to clip those corners as well, or they will "bleed" outside the rounded corners.
Give this a try (only slightly modified). It's designated #IBDesignable so you can see how it looks in Storyboard / Interface Builder (I did not set any of the properties to inspectable -- I'll leave that up to you if you want to do so):
#IBDesignable
class MyRSButton: UIButton {
var shouldApplyShadow: Bool = true
var innerShadows: Bool?
var cornerRadi: CGFloat = 8.0
var shadowLayer: CAShapeLayer!
var shadowRadius: CGFloat?
var shadowColor: UIColor?
var shadowOffset: CGSize?
var shadowOpacity: Float?
override func layoutSubviews() {
super.layoutSubviews()
applyShadow()
}
private func applyShadow() {
// needed to prevent background color from bleeding past
// the rounded corners
cornerRadi = bounds.size.height * 0.5
layer.cornerRadius = cornerRadi
layer.masksToBounds = false
if shouldApplyShadow && shadowLayer == nil {
shadowLayer = CAShapeLayer()
let shapePath = CGPath(roundedRect: bounds, cornerWidth: cornerRadi, cornerHeight: cornerRadi, transform: nil)
shadowLayer.path = shapePath
shadowLayer.fillColor = backgroundColor?.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowRadius = shadowRadius ?? 8
shadowLayer.shadowColor = (shadowColor ?? .black).cgColor
shadowLayer.shadowOffset = shadowOffset ?? CGSize(width: 0, height: 0)
shadowLayer.shadowOpacity = shadowOpacity ?? 0.8
layer.insertSublayer(shadowLayer!, at: 0)
/// If there's background color, there is no need to mask inner shadows.
if backgroundColor != .none && !(innerShadows ?? false) {
let maskLayer = CAShapeLayer()
maskLayer.path = { () -> UIBezierPath in
let path = UIBezierPath()
path.append(UIBezierPath(cgPath: shapePath))
// define a rect that is 80-pts wider and taller
// than the button... this will "expand" it from center
let r = bounds.insetBy(dx: -40, dy: -40)
path.append(UIBezierPath(rect: r))
path.usesEvenOddFillRule = true
return path
}().cgPath
maskLayer.fillRule = .evenOdd
shadowLayer.mask = maskLayer
}
}
}
}
Result:

Swift - Shadow for a irregular shape of a View

i am struggling to add shadow to a custom shape.
Here is a picture of what i want to construct:
(Dont mind the text and the symbol)
You can see the custom shape with the curved corner on the right and the rectangular shape on the left with shadow.
I am using UIView, and added corner to the left.
This is the code i have so far that shape the view correct:
View1.backgroundColor = .green //green color is just to see the shape well
let path = UIBezierPath(roundedRect:View1.bounds,
byRoundingCorners:[.topRight, .bottomRight],
cornerRadii: CGSize(width: self.frame.height/2, height: self.frame.height/2))
let maskLayer = CAShapeLayer()
I Have tried to add shadow to it, but the shadow does not apear.
Here is the code i have tried to add shadow:
View1.layer.masksToBounds = false
View1.layer.layer.shadowPath = maskLayer.path
View1.layer.shadowColor = UIColor.black.cgColor
View1.layer.shadowOffset = CGSize(width: 0.0, height: 3.0)
View1.layer.shadowOpacity = 0.5
View1.layer.shadowRadius = 1.0
How can you add shadow to this shape?
You can achieve this by using a single UIView (shadowView), adding a shapeLayer sublayer and setting the shadow of the shadowView's layer.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
#IBOutlet var shadowView: UIView!
func setup() {
// setup irregular shape
let path = UIBezierPath.init(roundedRect: shadowView.bounds, byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize.init(width: 20, height: 20))
let layer = CAShapeLayer.init()
layer.frame = shadowView.bounds
layer.path = path.cgPath
layer.fillColor = UIColor.white.cgColor
layer.masksToBounds = true
shadowView.layer.insertSublayer(layer, at: 0)
// setup shadow
shadowView.layer.shadowRadius = 8
shadowView.layer.shadowOpacity = 0.2
shadowView.layer.shadowOffset = CGSize.init(width: 0, height: 2.5)
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowPath = path.cgPath
}
}
Note:
The shadowView.clipToBounds must be false for the shadows to take effect.
To see the layer.fillColor, set the shadowView.backgroundColor to .clear.
You can easily achieve the above via Interface Builder by setting the 'Background' property and unchecking the 'Clip to Bounds' checkbox.

How to add shadow only for the border?

I want to add shadow around collectionview cells. But the shadow is around the images and labels in the cell, and no shadow around the cell. Does someone know how to work it out?
cell.contentView.layer.cornerRadius = 2.0
cell.contentView.layer.borderWidth = 1.0
cell.contentView.layer.borderColor = UIColor.clear.cgColor
cell.contentView.layer.masksToBounds = true
cell.layer.masksToBounds = false
cell.layer.shadowColor = UIColor.black.cgColor
cell.layer.shadowOpacity = 0.5
cell.layer.shadowOffset = CGSize(width: -1, height: 1)
cell.layer.shadowRadius = 1
Shadow around the content(not the border)
You are applying shadow to contentView directly hence it is not working. You need to take a view inside your contentView, put all your content in this view and give some padding (e.g. 8pt) from all side.
Suppose I have named this view as vwContainer, then:
#IBOutlet weak var vwContainer: UIView!
let shadowPath = UIBezierPath(rect: vwContainer.bounds)
vwContainer.layer.masksToBounds = false
vwContainer.layer.shadowColor = UIColor.blackColor().CGColor
vwContainer.layer.shadowOffset = CGSizeMake(0.0, 5.0)
vwContainer.layer.shadowOpacity = 0.5
vwContainer.layer.shadowPath = shadowPath.CGPath
If you are trying to achieve any other UI than please update your question with image.
extension UIView {
func addShadow(color: UIColor, radius: CGFloat = 1, offset: CGSize) {
self.layoutIfNeeded()
self.layer.masksToBounds = false
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = 0.5
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
Use it as:
let offset = CGSize(width: -1, height: 1)
cell.addShadow(color: .black, offset: offset)
You need to set background color for the contentView as below
cell.contentView.backgroundColor = .white

Set Shadow on Bottom UIView only

I want to create bottom only shadow on UIView. Right now with this function, will create shadow in top, bottom, left, and right.
func setCardView(view : UIView){
view.layer.masksToBounds = false
view.layer.shadowOffset = CGSize(width: 0, height: 0)
view.layer.shadowRadius = 2
view.layer.shadowOpacity = 0.5
}
Is there anyway to only create shadow in the bottom?
Any help would be appreciated. Thank you!
I think the proper way of thinking of shadow is, the shadow belongs to the object, which is the button, the uiview, not just part of the side. Imagining there is a virtual light source. You can't really just create a shadow for one side.
With that being said, the shadow will always be the shadow of the view as a whole. However, you can change the shadow offset to make it towards to the bottom.
view.layer.shadowOffset = CGSize(width: 0, height: 3)
This means you want the light source shoot the light from top to make the shadow to the bottom. The reason you still see some shadow at the top is the shadow radius. which is to simulate the diffuse of the light. The more diffuse the light is, the softer the shadow will be so you will see top shadow still.
view.layer.shadowRadius = 1 or 0.5
try to reduce the radius also. it will give you a better visual result.
To understand umbra, penumbra and antumbra if you need, check out https://en.wikipedia.org/wiki/Umbra,_penumbra_and_antumbra
This adds a shadow only to bottom. Implemented as an extension to UIView
extension UIView {
func addBottomShadow() {
layer.masksToBounds = false
layer.shadowRadius = 4
layer.shadowOpacity = 1
layer.shadowColor = UIColor.gray.cgColor
layer.shadowOffset = CGSize(width: 0 , height: 2)
layer.shadowPath = UIBezierPath(rect: CGRect(x: 0,
y: bounds.maxY - layer.shadowRadius,
width: bounds.width,
height: layer.shadowRadius)).cgPath
}
}
This code working for swift 4 and shadow applying for view Bottom:
view.layer.masksToBounds = false
view.layer.shadowRadius = 4
view.layer.shadowOpacity = 1
view.layer.shadowColor = UIColor.gray.cgColor
view.layer.shadowOffset = CGSize(width: 0 , height:2)
If you really want a shadow only on one side of your UIView, you should set your view.layer.shadowPath to a UIBezierPath.
Here is an example which will only display a shadow at the bottom of the view:
view.layer.shadowPath = UIBezierPath(rect: CGRect(x: 0,
y: bounds.maxY - layer.shadowRadius,
width: bounds.width,
height: layer.shadowRadius)).cgPath
Deconstructing the CGRect value, you get:
x and width make sure the shadow takes the full horizontal width of your view (you might want to adjust them, for example using the layer.shadowRadius value as a basis for your offsetting)
y and height make sure the shadow starts as low as possible and then is only as big as the radius
Of course, there are some cases where this won't work, for example when you want a shadowRadius larger than your view's height. In these cases, I would recommend using an image view or a masked layer.
Hope this helps,
Change your shadowOffset
view.layer.shadowOffset = CGSize(width: 0, height: 3)
Here's the proper way of applying shadow in Swift:
yourView.layer.shadowOffset = CGSize(width: 0, height: 3)
yourView.layer.shadowOpacity = 0.6
yourView.layer.shadowRadius = 3.0
yourView.layer.shadowColor = UIColor.red.cgColor
Old question but it seems none of the answers really answer the question.
While the above answers will work with a low shadowRadius you don't really get a 'shadow' effect.
You can absolutely add a shadow to just the bottom by using UIBezierPath
Heres how -
let shadowWidth: CGFloat = 1.2 // Shadow width, will be the width furthest away from the view, this is equivalent to 120% of the views width
let shadowHeight: CGFloat = 0.3 // Shadow height, again this is equivalent to 30%
let shadowRadius: CGFloat = 5
let width = someView.frame.width
let height = someView.frame.height // Get width and height of the view
// Plot the path
let shadowPath = UIBezierPath()
shadowPath.move(to: CGPoint(x: shadowRadius / 2, y: height - shadowRadius / 2))
shadowPath.addLine(to: CGPoint(x: width - shadowRadius / 2, y: height - shadowRadius / 2))
shadowPath.addLine(to: CGPoint(x: width * shadowWidth, y: height + (height * shadowHeight)))
shadowPath.addLine(to: CGPoint(x: width * -(shadowWidth - 1), y: height + (height * shadowHeight)))
// Add shadow
someView.layer.shadowPath = shadowPath.cgPath
someView.layer.shadowRadius = shadowRadius
someView.layer.shadowOffset = .zero
someView.layer.shadowOpacity = 0.2
This outputs this
Or if you wanted a simpler solution, with less options you could go with this
let buttonHeight = someButton.frame.height
let buttonWidth = someButton.frame.width
let shadowSize: CGFloat = 15
let contactRect = CGRect(x: -shadowSize, y: buttonHeight - (shadowSize * 0.2), width: buttonWidth + shadowSize * 2, height: shadowSize)
someButton.layer.shadowPath = UIBezierPath(ovalIn: contactRect).cgPath
someButton.layer.shadowRadius = 5
someButton.layer.shadowOpacity = 0.6
Which will output this
Example here
https://github.com/hemo87/ExampleShadow/tree/master
class ViewBottomShadow: UIView {
init() {
super.init(frame: .zero)
backgroundColor = .white
layer.masksToBounds = false
layer.shadowRadius = 2
layer.shadowOpacity = 1
layer.shadowColor = UIColor.gray.cgColor
layer.shadowOffset = CGSize(width: 0 , height:2)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Just draw regular shadow and rotate it upside down, as simple as that
#objc func shadowView() -> UIView {
let shadowView = UIView(frame: .zero)
shadowView.backgroundColor = .white
shadowView.layer.shadowColor = UIColor.grey.cgColor
shadowView.layer.shadowOffset = CGSize(width: 0, height: 2)
shadowView.layer.shadowOpacity = 1.0
shadowView.layer.shadowRadius = 4
shadowView.layer.compositingFilter = "multiplyBlendMode"
return shadowView
}
func idtm_addBottomShadow() {
let shadow = shadowView()
shadow.transform = transform.rotated(by: 180 * CGFloat(Double.pi))
shadow.transform = transform.rotated(by: -1 * CGFloat(Double.pi))
shadow.translatesAutoresizingMaskIntoConstraints = false
addSubview(shadow)
NSLayoutConstraint.activate([
shadow.leadingAnchor.constraint(equalTo: leadingAnchor),
shadow.trailingAnchor.constraint(equalTo: trailingAnchor),
shadow.bottomAnchor.constraint(equalTo: bottomAnchor),
shadow.heightAnchor.constraint(equalToConstant: 1),
])
}

Resources