Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách vẽ bóng đổ (shadow) dưới UIView trong iOS

Để làm cho giao diện người dùng (UI) hấp dẫn hơn, chúng ta thường thao tác với nhiều thuộc tính trong phát triển iOS. Để vẽ bóng xung quanh hoặc dưới một View, chúng ta cần làm việc với Layer và View.

Phương pháp 1: Viết mã trực tiếp tại chỗ cần thiết

self.layer.masksToBounds = false
self.layer.cornerRadius = 2
self.layer.shadowOffset = CGSize(width: -5, height: 10)
self.layer.shadowRadius = 3
self.layer.shadowOpacity = 0.3

Giải thích:

  • masksToBounds = false: Cho phép bóng hiển thị bên ngoài bounds của view (quan trọng!)
  • shadowOffset: Độ dịch chuyển của bóng (x, y)
  • shadowRadius: Độ mờ của bóng
  • shadowOpacity: Độ trong suốt của bóng (0.0 - 1.0)

Phương pháp 2: Tạo @IBDesignable và @IBInspectable để dùng với Storyboard

Tạo class DesignableView và extension UIView để các thuộc tính bóng có thể chỉnh sửa trực tiếp trên Storyboard:

@IBDesignable class DesignableView: UIView { }

extension UIView {
    @IBInspectable
    var shadowRadius: CGFloat {
        get { return layer.shadowRadius }
        set { layer.shadowRadius = newValue }
    }
    
    @IBInspectable
    var shadowOpacity: Float {
        get { return layer.shadowOpacity }
        set { layer.shadowOpacity = newValue }
    }
    
    @IBInspectable
    var shadowOffset: CGSize {
        get { return layer.shadowOffset }
        set { layer.shadowOffset = newValue }
    }
    
    @IBInspectable
    var shadowColor: UIColor? {
        get {
            if let color = layer.shadowColor {
                return UIColor(cgColor: color)
            }
            return nil
        }
        set {
            layer.shadowColor = newValue?.cgColor
        }
    }
}

Sử dụng extension này, bạn có thể điều chỉnh bóng của bất kỳ UIView nào trực tiếp trên Storyboard. Thay đổi sẽ hiển thị ngay lập tức (live rendering) mà không cần chạy ứng dụng.

Cách vẽ bóng đổ (shadow) dưới UIView trong iOS

Lưu ý quan trọng: Khi sử dụng shadow, nhớ đặt masksToBounds = false (hoặc không đặt, mặc định là false). Nếu đặt clipsToBounds = true hoặc masksToBounds = true, bóng sẽ bị cắt mất.