Draw a simple circle uiimage

前端 未结 6 1488
遥遥无期
遥遥无期 2020-12-28 12:33

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

6条回答
  •  囚心锁ツ
    2020-12-28 13:06

    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.

提交回复
热议问题