[ios] How to set corner radius of imageView?

In Objective-C such line

self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame)/4.0f;

does its job, I tried it in Swift using analogy

self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame)/4.0

and it doesn't change anything, the corners are the same as before. Moreover, Xcode does not show any syntax errors. Does Swift support any other way to reach this goal? I checked some other threads here and usually it's getting done in Swift in the way showed above.

This question is related to ios swift uiimageview cornerradius

The answer is


You can define border radius of any view providing an "User defined Runtime Attributes", providing key path "layer.cornerRadius" of type string and then the value of radius you need ;) See attached images below:

Configuring in XCode

Result in emulator


Marked with @IBInspectable in swift (or IBInspectable in Objective-C), they are easily editable in Interface Builder’s attributes inspector panel.
You can directly set borderWidth,cornerRadius,borderColor in attributes inspector

extension UIView {

  @IBInspectable var cornerRadius: CGFloat {

   get{
        return layer.cornerRadius
    }
    set {
        layer.cornerRadius = newValue
        layer.masksToBounds = newValue > 0
    }
  }

  @IBInspectable var borderWidth: CGFloat {
    get {
        return layer.borderWidth
    }
    set {
        layer.borderWidth = newValue
    }
  }

  @IBInspectable var borderColor: UIColor? {
    get {
        return UIColor(cgColor: layer.borderColor!)
    }
    set {
        layer.borderColor = borderColor?.cgColor
    }
  }
}

enter image description here


import UIKit

class BorderImage: UIImageView {

    override func awakeFromNib() {
        self.layoutIfNeeded()
        layer.cornerRadius = self.frame.height / 10.0
        layer.masksToBounds = true
    }
}

Based on @DCDC's answer


I created an UIView extension which allows to round specific corners :

import UIKit

enum RoundType {
    case top
    case none
    case bottom
    case both
}

extension UIView {

    func round(with type: RoundType, radius: CGFloat = 3.0) {
        var corners: UIRectCorner

        switch type {
        case .top:
            corners = [.topLeft, .topRight]
        case .none:
            corners = []
        case .bottom:
            corners = [.bottomLeft, .bottomRight]
        case .both:
            corners = [.allCorners]
        }

        DispatchQueue.main.async {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            self.layer.mask = mask
        }
    }

}

Swift 3, Xcode 8, iOS 10

DispatchQueue.main.async {
  self.mainImageView.layer.cornerRadius = self.mainImageView.bounds.size.width / 2.0
  self.mainImageView.clipsToBounds = true
}

The easiest way is to create an UIImageView subclass (I have tried it and it's working perfectly on iPhone 7 and XCode 8):

class CIRoundedImageView: UIImageView {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {

        self.layoutIfNeeded()
        layer.cornerRadius = self.frame.height / 2.0
        layer.masksToBounds = true
    }
}

and then you can also set a border:

imageView.layer.borderWidth = 2.0

imageView.layer.borderColor = UIColor.blackColor().CGColor

There is one tiny difference in Swift 3.0 and Xcode8

Whenever you want to apply corner radius to UIView, make sure you call yourUIView.layoutIfNeeded() before calling cornerRadius.

Otherwise, it will return the default value for UIView's height and width (1000.0) which will probably make your View disappear.

Always make sure that all effects that changes the size of UIView (Interface builder constraints etc) are applied before setting any layer properties.

Example of UIView class implementation

class BadgeView: UIView {

  override func awakeFromNib() {

    self.layoutIfNeeded()
    layer.cornerRadius = self.frame.height / 2.0
    layer.masksToBounds = true

   }
 }

in swift 3 'CGRectGetWidth' has been replaced by property 'CGRect.width'

    view.layer.cornerRadius = view.frame.width/4.0
    view.clipsToBounds = true

try this

self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame)/4.0
self.mainImageView.clipsToBounds = true

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to uiimageview

Programmatically change the height and width of a UIImageView Xcode Swift How to set image in circle in swift How to load GIF image in Swift? How to assign an action for UIImageView object in Swift How to set corner radius of imageView? How do you create a UIImage View Programmatically - Swift UIImageView aspect fit and center Resize UIImage and change the size of UIImageView How to view .img files? iOS - UIImageView - how to handle UIImage image orientation

Examples related to cornerradius

How to set corner radius of imageView? How to set cornerRadius for only top-left and top-right corner of a UIView?