Draw a simple circle uiimage

前端 未结 6 1536
遥遥无期
遥遥无期 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 12:59

    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)
        }
    }
    

提交回复
热议问题