Dibujar un círculo simple uiimage


Trato de hacer una imagen de 20x20 con un simple círculo azul. Intento con esta función, pero el resultado es un círculo azul en un cuadrado negro. ¿Cómo elimino el cuadrado negro alrededor del círculo?

Función:

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

Resultado Real: introduzca la descripción de la imagen aquí

Author: Cœur, 2013-11-21

6 answers

Necesitas incluir el canal alfa en tu mapa de bits: UIGraphicsBeginImageContextWithOptions(..., NO, ...) si quieres ver lo que hay detrás de las esquinas.

 30
Author: yurish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-21 10:00:56

¡Gracias por las preguntas y respuestas! Código Swift como se muestra a continuación:

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 versión proporcionada por 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
    }
}
 31
Author: superarts.org,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-14 03:52:10

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

La autocorrección rápida es piadosa. Gracias a Valentin.

 8
Author: Schemetrical,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-24 18:23:37

Xamarin.Ejemplo de 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;
    }
 2
Author: Jelle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-24 10:26:17

Prueba esto

UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
 1
Author: Amr Angry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-24 15:34:29

Un inicializador personalizado para crear un círculo con un diámetro y color específicos:

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)
    }
}
 0
Author: CodeBender,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-30 17:09:38