ใช้ layer.cornerRadius และ clipsToBounds = true ทำให้ UIImageView หรือ View ใดๆ มีมุมโค้ง
วิธีพื้นฐาน
let imageView = UIImageView(image: UIImage(named: "photo"))
imageView.frame = CGRect(x: 20, y: 50, width: 200, height: 200)
imageView.contentMode = .scaleAspectFill
// ทำมุมโค้ง
imageView.layer.cornerRadius = 20
imageView.clipsToBounds = true // สำคัญ! ต้องเป็น true
view.addSubview(imageView)
Extension UIImageView
extension UIImageView {
func roundCorners(radius: CGFloat) {
layer.cornerRadius = radius
clipsToBounds = true
}
func makeCircular() {
layer.cornerRadius = min(bounds.width, bounds.height) / 2
clipsToBounds = true
}
}
// ใช้งาน
imageView.roundCorners(radius: 15)
// หรือ
imageView.makeCircular() // วงกลมสมบูรณ์
Storyboard (User Defined Runtime Attributes)
- Select Image View → Identity Inspector
- User Defined Runtime Attributes → +
- Key Path:
layer.cornerRadius, Type: Number, Value:20 - Key Path:
layer.masksToBounds, Type: Boolean, Value:true
Rounded Corners เฉพาะบางมุม (iOS 11+)
// เฉพาะมุมบนซ้ายและบนขวา
imageView.layer.cornerRadius = 20
imageView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
imageView.clipsToBounds = true
// MaskedCorners Options:
// .layerMinXMinYCorner - Top Left
// .layerMaxXMinYCorner - Top Right
// .layerMinXMaxYCorner - Bottom Left
// .layerMaxXMaxYCorner - Bottom Right
Performance Note
clipsToBounds = trueทำให้ Offscreen Rendering (อาจช้าเล็กน้อย)- ใช้
layer.shouldRasterize = true; layer.rasterizationScale = UIScreen.main.scaleช่วย Performance - หรือใช้
UIBezierPath + CAShapeLayerเป็น Mask แทน (Complex)
SwiftUI
Image("photo")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 200, height: 200)
.clipShape(RoundedRectangle(cornerRadius: 20))
// หรือ
.clipShape(Circle())