画一个简单的圆形uiimage

我试图做一个简单的蓝色圆圈的20×20 UIImage。 我尝试使用这个函数,但结果是在一个黑色的方形蓝圈。 如何去除圆周上的黑色方块?

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

实际结果: 在这里输入图像说明

你需要在你的位图中包含alpha通道: UIGraphicsBeginImageContextWithOptions(..., NO, ...)如果你想看看angular落后面的东西。

感谢您的问答! Swift代码如下:

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

Scheme:提供的Swift 3版本:

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

迅速自动更正是敬虔的。 感谢瓦伦丁。

Xamarin.iOS示例:

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

尝试这个

 UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);