iphoneuiviewuiimageviewgeometryquartz-core

How to make a circular UIView


I want to make a UIView or UIImageView that is a circle. Or a circle that i can change the size of using a slider, and the color of with a pickerview.


Solution

  • As mentioned in some comments, @IBDesignable makes this much easier now, so you can use Interface Builder to configure your rounded UIImageView.

    First create a class named RoundedImageView.swift and paste this code to it:

    import UIKit
    
    @IBDesignable public class RoundedImageView: UIImageView {
    
        override public func layoutSubviews() {
            super.layoutSubviews()
    
            //hard-coded this since it's always round
            layer.cornerRadius = 0.5 * bounds.size.width
        }
    }
    

    Select the UIImageView in InterfaceBuilder and change the class from UIImageView to the custom RoundedImageView:

    enter image description here

    Set Clip to Bounds to true (or the pic will extend beyond the circle):

    enter image description here

    It should now round itself right there in InterfaceBuilder, which is pretty nifty. Be sure to set the width and height to the same values or it'll be shaped like a zeppelin!

    enter image description here