41

I try to make a 20x20 UIImage with a simple blue circle. I try with this function, but the result is a blue circle in a black square. How do I remove the black square around the circle?

Function:

+ (UIImage *)blueCircle {
    static UIImage *blueCircle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(20.f, 20.f), YES, 0.0f);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSaveGState(ctx);

        CGRect rect = CGRectMake(0, 0, 20, 20);
        CGContextSetFillColorWithColor(ctx, [UIColor cyanColor].CGColor);
        CGContextFillEllipseInRect(ctx, rect);

        CGContextRestoreGState(ctx);
        blueCircle = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

    });
    return blueCircle;
}

actual result: enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
matti157
  • 1,288
  • 2
  • 13
  • 26
  • 1
    Potentially you should use a view rather than an imageview http://stackoverflow.com/questions/6589265/how-to-draw-a-custom-uiview-that-is-just-a-circle-iphone-app – Woodstock Nov 21 '13 at 09:06

8 Answers8

38

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
    }
}
superarts.org
  • 7,009
  • 1
  • 58
  • 44
34

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

yurish
  • 1,515
  • 1
  • 15
  • 16
20

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.

Shrawan
  • 7,128
  • 4
  • 29
  • 40
Schemetrical
  • 5,506
  • 2
  • 26
  • 43
4

I just want to add that the most simple and sexy way of drawing shapes and have them as rastered images (with transparent background) that I found is the way how Paul Hudson did it on his hackingwithswift.com website.

https://www.hackingwithswift.com/example-code/core-graphics/how-to-draw-a-circle-using-core-graphics-addellipsein

Snippet from the site:

let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
let img = renderer.image { ctx in
    ctx.cgContext.setFillColor(UIColor.red.cgColor)
    ctx.cgContext.setStrokeColor(UIColor.green.cgColor)
    ctx.cgContext.setLineWidth(10)

    let rectangle = CGRect(x: 0, y: 0, width: 512, height: 512)
    ctx.cgContext.addEllipse(in: rectangle)
    ctx.cgContext.drawPath(using: .fillStroke)
}
Heps
  • 945
  • 9
  • 24
2

Xamarin.iOS sample:

    public static UIImage CircleImage(nfloat diameter, UIColor color, bool opaque = false)
    {
        var rect = new CGRect(0, 0, diameter, diameter);

        UIGraphics.BeginImageContextWithOptions(rect.Size, opaque, 0);
        var ctx = UIGraphics.GetCurrentContext();
        ctx.SaveState();

        ctx.SetFillColor(color.CGColor);
        ctx.FillEllipseInRect(rect);

        ctx.RestoreState();
        var img = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return img;
    }
Jelle
  • 365
  • 3
  • 11
1

Try this

UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Amr Angry
  • 3,711
  • 1
  • 45
  • 37
1

A custom initializer for creating a circle with a specific diameter and color:

extension UIImage {
    convenience init?(diameter: CGFloat, color: UIColor) {
        let size = CGSize(width: diameter, height: diameter)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        guard let contex = UIGraphicsGetCurrentContext() else {
            return nil
        }

        contex.saveGState()
        let rect = CGRect(origin: .zero, size: size)
        contex.setFillColor(color.cgColor)
        contex.fillEllipse(in: rect)
        contex.restoreGState()

        guard let image = UIGraphicsGetImageFromCurrentImageContext(),
        let cgImage = image.cgImage else {
            return nil
        }
        UIGraphicsEndImageContext()

        self.init(cgImage: cgImage)
    }
}
CodeBender
  • 35,668
  • 12
  • 125
  • 132
0

I think it's slightly nicer to do this with a convenience init and the UIGraphicsImageRenderer

public extension UIImage {
        
        convenience init?(circleDiameter: CGFloat, color: UIColor) {
            
            let size = CGSize(width: circleDiameter, height: circleDiameter)
            
            let renderer = UIGraphicsImageRenderer(size: size)
            
            let image = renderer.image { (ctx) in
                color.setFill()
                ctx.cgContext.fillEllipse(in: CGRect(origin: .zero, size: size))
            }
            
            guard let cgImage = image.cgImage else {
                return nil
            }
            
            self.init(cgImage: cgImage)
        }
    }
Mark Bridges
  • 8,228
  • 4
  • 50
  • 65