Draw a simple circle uiimage

前端 未结 6 1534
遥遥无期
遥遥无期 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:48

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

提交回复
热议问题