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

Cách đặt độ trong suốt (opacity/alpha) cho View trong iOS

Thuộc tính alpha của UIView (kế thừa từ CALayer) nhận giá trị 0.0 - 1.0:

  • 0.0 = Hoàn toàn trong suốt (invisible)
  • 1.0 = Hoàn toàn đặc (opaque - mặc định)

Cách 1: View Alpha (Làm trong suốt cả view + nội dung con)


override func viewDidLoad() {
    super.viewDidLoad()
    
    // Cả view và subviews đều mờ 50%
    view.alpha = 0.5
    
    // Hoặc animate
    UIView.animate(withDuration: 0.3) {
        self.view.alpha = 0.5
    }
}

Cách 2: Background Color Alpha (Chỉ làm trong suốt nền, giữ nội dung rõ)


override func viewDidLoad() {
    super.viewDidLoad()
    
    // Chỉ nền mờ 50%, text/image con vẫn rõ
    view.backgroundColor = UIColor(white: 1, alpha: 0.5) // Trắng 50%
    // Hoặc
    view.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.5)
    // Hoặc màu custom
    view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) // Đen 30%
}

Cách đặt độ trong suốt (opacity/alpha) cho View trong iOS

So sánh: alpha vs backgroundColor alpha

  • Fade in/out toàn bộ view
  • Disabled state cho container
  • Overlay mờ, glassmorphism
  • Giữ text/button con rõ ràng
  • Thuộc tính Ảnh hưởng đến Use case
    view.alpha Cả view + tất cả subviews (text, image, button...)
    view.backgroundColor = UIColor(..., alpha: x) Chỉ background của view đó

    Cách 3: Layer Opacity (Core Animation)

    
    // Tương tự view.alpha nhưng ở layer level
    view.layer.opacity = 0.5
    // Dùng khi cần animation phức tạp với CABasicAnimation
    

    Ví dụ thực tế: Overlay loading

    
    func showLoadingOverlay() {
        let overlay = UIView(frame: view.bounds)
        overlay.backgroundColor = UIColor.black.withAlphaComponent(0.4)
        overlay.alpha = 0
        overlay.tag = 999
        
        let indicator = UIActivityIndicatorView(style: .large)
        indicator.color = .white
        indicator.center = overlay.center
        indicator.startAnimating()
        overlay.addSubview(indicator)
        
        view.addSubview(overlay)
        
        UIView.animate(withDuration: 0.2) {
            overlay.alpha = 1
        }
    }
    
    func hideLoadingOverlay() {
        if let overlay = view.viewWithTag(999) {
            UIView.animate(withDuration: 0.2, animations: {
                overlay.alpha = 0
            }) { _ in
                overlay.removeFromSuperview()
            }
        }
    }
    

    Lưu ý

    • alpha = 0 khác isHidden = true: alpha=0 vẫn nhận touch, isHidden không nhận touch
    • Performance: Alpha < 1.0 trigger offscreen rendering (có thể giảm FPS nếu lạm dụng)
    • iOS 13+: Ưu tiên UIColor.systemBackground.withAlphaComponent() để hỗ trợ Dark Mode
    • Nested alpha: Con alpha * Cha alpha = alpha thực tế (multiplicative)