Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีแสดงรูปภาพมุมโค้ง (Rounded Corners) ใน iOS App ด้วย Swift

ใช้ 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)

  1. Select Image View → Identity Inspector
  2. User Defined Runtime Attributes → +
  3. Key Path: layer.cornerRadius, Type: Number, Value: 20
  4. 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())