shadow on a roundedrectangle in swift

To add a shadow to a rounded rectangle, you can use the CALayer property called shadowOpacity, shadowRadius, shadowOffset, and shadowColor. Here is a sample code that shows you how to add round corners with a shadow in Swift:

main.swift
import UIKit

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    let rect = CGRect(x: 50, y: 50, width: 200, height: 100)
    let roundedRect = UIBezierPath(roundedRect: rect, cornerRadius: 20)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = roundedRect.cgPath
    shapeLayer.fillColor = UIColor.green.cgColor
    shapeLayer.shadowOpacity = 0.5
    shapeLayer.shadowRadius = 5
    shapeLayer.shadowOffset = CGSize(width: 0, height: 3)
    shapeLayer.shadowColor = UIColor.black.cgColor

    view.layer.addSublayer(shapeLayer)
  }

}
596 chars
23 lines

This code creates a rounded rectangle using UIBezierPath, sets its fillColor to green, and adds it as a sublayer to the view's layer. It also sets the shadowOpacity, shadowRadius, shadowOffset, and shadowColor properties of the layer to create the shadow effect. You can adjust these properties as needed to get the desired result.

gistlibby LogSnag