Establecer Un Fondo Transparente CGContext


Todavía estoy luchando con dibujar una línea con CGContext. En realidad tengo que ir a la línea para dibujar, pero ahora necesito que el fondo del Recto sea transparente para que el fondo existente se muestre a través. Aquí está mi código de prueba:

(void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
    CGContextSetAlpha(context,0.0);
    CGContextFillRect(context, rect);

    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(context, 5.0);
    CGContextMoveToPoint(context, 100.0,0.0);
    CGContextAddLineToPoint(context,100.0, 100.0);
    CGContextStrokePath(context);
}

¿Alguna idea?

Author: Codebeef, 2010-01-24

8 answers

Después de UIGraphicsGetCurrentContext() llamar CGContextClearRect(context,rect)

Editar: Muy bien, lo tengo.

Su vista personalizada con la línea debe tener lo siguiente:

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(context, 5.0);
    CGContextMoveToPoint(context, 100.0,0.0);
    CGContextAddLineToPoint(context,100.0, 100.0);
    CGContextStrokePath(context);
}

Mi prueba usó esto como un controlador UIViewController muy básico:

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView *v = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [v setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:v];
    TopView *t = [[TopView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:t];
    [v release];
    [t release];
}
 70
Author: David Kanarek,
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
2010-01-24 17:57:31

Manera fácil:

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {       
        self.opaque = NO;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    //your code
}
 40
Author: ZGl6YXNt,
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
2012-09-17 01:49:08

Esto es lo que funcionó para mí con un UIImage que se había añadido manualmente usando InterfaceBuilder.

- (id)initWithCoder:(NSCoder *)aDecoder {

    if(self = [super initWithCoder:aDecoder]) {
        self.backgroundColor = [UIColor clearColor];
    }

    return self;
}


-(void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();    
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(context, 5.0);
    CGContextMoveToPoint(context, 100.0,0.0);
    CGContextAddLineToPoint(context,100.0, 100.0);
    CGContextStrokePath(context);
}

La respuesta de David Kanarek solo funciona cuando estás creando manualmente tu propia UIImageView. Si ha creado un UIView y lo ha añadido manualmente a través de Interface Builder, necesitará un enfoque diferente como este llamando al método initWithCoder en su lugar.

 4
Author: Patrick Collins,
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
2014-11-22 22:18:51

Tengo el mismo problema, entonces me parece que es. Sobrescribo el método init es -(id)initWithFrame:(CGRect)rect. En este método self.background = [UIColor clearColor]; pero yo uso esta vista en el archivo xib!!! Que llamará al método init es

-(id)initWithCoder:(NSCoder*)aDecoder;

Así que sobrescribir todo el método init y configurar backgroundColor funcionará bien.

 3
Author: en-菜鸟..,
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
2012-10-21 07:38:01
CGContextClearRect(context,rect) 

Si el contexto proporcionado es un contexto de ventana o mapa de bits, Quartz borra efectivamente el rectángulo. Para otros tipos de contexto, el cuarzo rellena el rectángulo de una manera dependiente del dispositivo. Sin embargo, no debe usar esta función en contextos que no sean contextos de ventana o de mapa de bits.

 2
Author: Codrut,
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
2011-09-26 09:25:56

Puede crear un contexto de imagen con este código:

cacheContext = CGBitmapContextCreate (cacheBitmap, size.width, size.height, 8, bitmapBytesPerRow, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast);
CGContextSetRGBFillColor(cacheContext, 0, 0, 0, 0);
CGContextFillRect(cacheContext, (CGRect){CGPointZero, size});

La clave es kCGImageAlphaPremultipliedLast.

 1
Author: fluke,
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-10-04 09:33:57

Tiene problemas para entender la pregunta aquí, pero si no puede tener una vista UIView "de fondo" a través de una vista "superior" en la que está dibujando, una solución es topView.backgroundColor = [UIColor clearColor]; Estaba teniendo (creo) este mismo problema y esto lo resolvió para mí.

 0
Author: oflannabhra,
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
2011-07-29 15:16:13

Init un contexto con opaque == false, Swift 3

UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) 

Opaco

Una bandera booleana que indica si el mapa de bits es opaco. Si sabe que el mapa de bits es completamente opaco, especifique true para ignorar el canal alfa y optimizar el almacenamiento del mapa de bits. Especificar false significa que el mapa de bits debe incluir un canal alfa para manejar cualquier píxel parcialmente transparente.

 0
Author: onmyway133,
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-06-22 10:37:25