Để 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)

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

3. Áp dụng cornerRadius + clipsToBounds
imageView.layer.cornerRadius = 20
imageView.clipsToBounds = true
Kết quả bo góc 20pt:

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 = truebắt buộc – nếu không, ảnh sẽ tràn ra ngoài góc bo.contentMode = .scaleAspectFillgiúp ảnh lấp đầy khung, tránh bị méo khi bo góc.- Performance:
clipsToBoundstrigger off-screen rendering. Với nhiều ảnh trong scroll view, cân nhắc dùnglayer.maskvớiCAShapeLayerpath 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.