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

Cách làm nền trong suốt 25% (alpha 0.25) trong iOS

Apple cung cấp thuộc tính backgroundColor cho UIView. Giá trị mặc định là nil (trong suốt hoàn toàn). Để tạo nền trong suốt 25%, ta đặt alpha = 0.25.

Cách thực hiện

Thêm dòng code sau vào viewDidLoad của ViewController:

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor(white: 1, alpha: 0.25)
}

Cách làm nền trong suốt 25% (alpha 0.25) trong iOS

Các biến thể khác

1. Màu đen trong suốt 50% (thường dùng cho overlay)

view.backgroundColor = UIColor(white: 0, alpha: 0.5)
// Hoặc
view.backgroundColor = UIColor.black.withAlphaComponent(0.5)

2. Màu tùy chỉnh với alpha

// RGB + Alpha
view.backgroundColor = UIColor(red: 0.2, green: 0.6, blue: 0.9, alpha: 0.3)

// Hex + Alpha (Swift 5+)
view.backgroundColor = UIColor(hex: "#3498DB", alpha: 0.25)

// Extension tiện ích
extension UIColor {
    convenience init(hex: String, alpha: CGFloat = 1.0) {
        var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
        hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
        
        var rgb: UInt64 = 0
        Scanner(string: hexSanitized).scanHexInt64(&rgb)
        
        let r = CGFloat((rgb & 0xFF0000) >> 16) / 255
        let g = CGFloat((rgb & 0x00FF00) >> 8) / 255
        let b = CGFloat(rgb & 0x0000FF) / 255
        
        self.init(red: r, green: g, blue: b, alpha: alpha)
    }
}

3. Chỉ làm trong suốt một view con (không ảnh hưởng view cha)

let overlayView = UIView(frame: view.bounds)
overlayView.backgroundColor = UIColor.black.withAlphaComponent(0.25)
view.addSubview(overlayView)

4. Animation thay đổi alpha

UIView.animate(withDuration: 0.3) {
    self.view.backgroundColor = UIColor(white: 1, alpha: 0.25)
}

Lưu ý

  • white: 1 = màu trắng, white: 0 = màu đen (grayscale)
  • Alpha từ 0.0 (trong suốt hoàn toàn) đến 1.0 (đặc hoàn toàn)
  • Để làm mờ cả nội dung con, dùng view.alpha = 0.25 (khác với backgroundColor alpha)
  • Trên iOS 13+, có thể dùng UIColor.systemBackground.withAlphaComponent(0.25) để thích ứng Dark Mode