0

I have this extension, which creates a square UIImage.

extension UIColor {
    func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { rendererContext in
        self.setFill()
        rendererContext.fill(CGRect(origin: .zero, size: size))
        }
    }
}

How can I return a circled UIImage?

JohnDole
  • 525
  • 5
  • 16
  • https://stackoverflow.com/questions/30368739/how-to-draw-a-simple-rounded-rect-in-swift-rounded-corners – Dilan Apr 21 '20 at 16:35

1 Answers1

1

Looking at CGContext methods there is a fillEllipse(in:). So instead of fill() (which make it fill all the image), we retrieve the cgContext of the rendererContext and call fillEllipse(in:) on it.

func circleImage(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
    return UIGraphicsImageRenderer(size: size).image(actions: { rendererContext in
        self.setFill()
        rendererContext.cgContext.fillEllipse(in: CGRect(origin: .zero, size: size))
    })
}

In Playground:

enter image description here

Larme
  • 24,190
  • 6
  • 51
  • 81
  • Hi, can not test it right now. But wouldnt this create a squared Image with round fill? I need a round UIImage, not just the color to be rounded – JohnDole Apr 21 '20 at 16:53
  • What do you need? A rounded square or a circle? This will create a colored circle if the size is a square and an elipse if it is a rectangle, with a transparent background. – Leo Dabus Apr 21 '20 at 16:55
  • Sorry. I need a circle. I will test your code, although I do now know where you make the UIImage circled here. I thought your code will produce a squared UIImage with a colored circle inside. – JohnDole Apr 21 '20 at 16:59
  • This produces a a circle with the rest being transparent. I added the render. – Larme Apr 21 '20 at 17:18