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

Cách hiển thị ảnh bo góc (rounded corners) trong iOS App Swift

Để bo góc ảnh (hoặc bất kỳ UIView nào) trong iOS, truy cập layer.cornerRadius và bật clipsToBounds = true (hoặc layer.masksToBounds = true).

1. Tạo UIImageView bằng code


func addImage(imageName: String) {
    let imageView = UIImageView()
    imageView.frame = CGRect(x: 10, y: 20, width: 200, height: 200)
    imageView.contentMode = .scaleAspectFill
    imageView.image = UIImage(named: imageName)
    view.addSubview(imageView)
}

2. Bo góc ảnh gốc (vuông)

Cách hiển thị ảnh bo góc (rounded corners) trong iOS App Swift

Hiển thị không bo góc:

Cách hiển thị ảnh bo góc (rounded corners) trong iOS App Swift

3. Áp dụng cornerRadius + clipsToBounds


imageView.layer.cornerRadius = 20
imageView.clipsToBounds = true

Kết quả bo góc 20pt:

Cách hiển thị ảnh bo góc (rounded corners) trong iOS App Swift

4. Extension UIImageView tái sử dụng


extension UIImageView {
    func makeRoundCorners(radius: CGFloat) {
        layer.cornerRadius = radius
        clipsToBounds = true
        contentMode = .scaleAspectFill  // Đảm bảo ảnh lấp đầy bounds
    }
}

// Sử dụng:
imageView.makeRoundCorners(radius: 20)
// Hoặc tròn hoàn toàn (hình tròn):
imageView.makeRoundCorners(radius: imageView.frame.width / 2)

5. Bo góc trên Storyboard (IBInspectable)

Dùng extension UIView từ bài trước (1003060622) – thêm @IBInspectable var cornerRadius – chỉnh trực tiếp trên Attribute Inspector.

Lưu ý quan trọng

  • clipsToBounds = true bắt buộc – nếu không, ảnh sẽ tràn ra ngoài góc bo.
  • contentMode = .scaleAspectFill giúp ảnh lấp đầy khung, tránh bị méo khi bo góc.
  • Performance: clipsToBounds trigger off-screen rendering. Với nhiều ảnh trong scroll view, cân nhắc dùng layer.mask với CAShapeLayer path bo góc, hoặc rasterize: layer.shouldRasterize = true; layer.rasterizationScale = UIScreen.main.scale.
  • Shadow + Rounded corners: Không dùng chung clipsToBounds (sẽ cắt shadow). Tách 2 layer: container view bo góc clipsToBounds, subview bên trong có shadow.