Draw a simple circle uiimage Draw a simple circle uiimage ios ios

Draw a simple circle uiimage


Thanks for the Q&A! Swift code as below:

extension UIImage {    class func circle(diameter: CGFloat, color: UIColor) -> UIImage {        UIGraphicsBeginImageContextWithOptions(CGSizeMake(diameter, diameter), false, 0)        let ctx = UIGraphicsGetCurrentContext()        CGContextSaveGState(ctx)        let rect = CGRectMake(0, 0, diameter, diameter)        CGContextSetFillColorWithColor(ctx, color.CGColor)        CGContextFillEllipseInRect(ctx, rect)        CGContextRestoreGState(ctx)        let img = UIGraphicsGetImageFromCurrentImageContext()        UIGraphicsEndImageContext()        return img    }}

Swift 3 version provided by Schemetrical:

extension UIImage {    class func circle(diameter: CGFloat, color: UIColor) -> UIImage {        UIGraphicsBeginImageContextWithOptions(CGSize(width: diameter, height: diameter), false, 0)        let ctx = UIGraphicsGetCurrentContext()!        ctx.saveGState()        let rect = CGRect(x: 0, y: 0, width: diameter, height: diameter)        ctx.setFillColor(color.cgColor)        ctx.fillEllipse(in: rect)        ctx.restoreGState()        let img = UIGraphicsGetImageFromCurrentImageContext()!        UIGraphicsEndImageContext()        return img    }}


You need to include alpha channel into your bitmap: UIGraphicsBeginImageContextWithOptions(..., NO, ...) if you want to see what is behind the corners.


Swift 3 & 4:

extension UIImage {    class func circle(diameter: CGFloat, color: UIColor) -> UIImage {        UIGraphicsBeginImageContextWithOptions(CGSize(width: diameter, height: diameter), false, 0)        let ctx = UIGraphicsGetCurrentContext()!        ctx.saveGState()        let rect = CGRect(x: 0, y: 0, width: diameter, height: diameter)        ctx.setFillColor(color.cgColor)        ctx.fillEllipse(in: rect)        ctx.restoreGState()        let img = UIGraphicsGetImageFromCurrentImageContext()!        UIGraphicsEndImageContext()        return img    }}

Swift autocorrect is godly. Thanks to Valentin.