14

Estoy intentando crear una máscara de imagen a partir de un compuesto de dos imágenes existentes.Crear máscara con CGImageMaskCreate es todo negro (iphone)

Primero comienzo con la creación de material compuesto que consiste en una pequeña imagen que es la imagen de máscara, y una imagen más grande, que es del mismo tamaño que el fondo:

UIImage * BaseTextureImage = [UIImage imageNamed:@"background.png"]; 
UIImage * MaskImage = [UIImage imageNamed:@"my_mask.jpg"]; 
UIImage * ShapesBase = [UIImage imageNamed:@"largerimage.jpg"]; 
UIImage * MaskImageFull; 

CGSize finalSize = CGSizeMake(480.0, 320.0); 
UIGraphicsBeginImageContext(finalSize); 
[ShapesBase drawInRect:CGRectMake(0, 0, 480, 320)]; 
[MaskImage drawInRect:CGRectMake(150, 50, 250, 250)]; 
MaskImageFull = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

me puede dar salida a este UIImage (MaskImageFull) y se ve bien, es un tamaño de fondo de tamaño completo y es un fondo blanco con el objeto de máscara en negro, en el lugar correcto en la pantalla.

Luego paso el MaskImageFull UIImage a través de este:

CGImageRef maskRef = [maskImage CGImage]; 
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef), 
    CGImageGetHeight(maskRef), 
    CGImageGetBitsPerComponent(maskRef), 
    CGImageGetBitsPerPixel(maskRef), 
    CGImageGetBytesPerRow(maskRef), 
    CGImageGetDataProvider(maskRef), NULL, false); 

CGImageRef masked = CGImageCreateWithMask([image CGImage], mask); 
UIImage* retImage= [UIImage imageWithCGImage:masked]; 

El problema es que el retImage es todo negro. Si envío un UIImage prefabricado como máscara funciona bien, es justo cuando intento hacerlo desde varias imágenes que se rompe.

Pensé que era una cuestión de espacio de colores pero no parecía poder solucionarlo. ¡Cualquier ayuda es muy apreciada!

Respuesta

19

Intenté lo mismo con CGImageCreateWithMask, y obtuve el mismo resultado. La solución que encontré fue utilizar CGContextClipToMask lugar:

CGContextRef mainViewContentContext; 
CGColorSpaceRef colorSpace; 

colorSpace = CGColorSpaceCreateDeviceRGB(); 

// create a bitmap graphics context the size of the image 
mainViewContentContext = CGBitmapContextCreate (NULL, targetSize.width, targetSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast); 

// free the rgb colorspace 
CGColorSpaceRelease(colorSpace);  

if (mainViewContentContext==NULL) 
    return NULL; 

CGImageRef maskImage = [[UIImage imageNamed:@"mask.png"] CGImage]; 
CGContextClipToMask(mainViewContentContext, CGRectMake(0, 0, targetSize.width, targetSize.height), maskImage); 
CGContextDrawImage(mainViewContentContext, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), self.CGImage); 


// Create CGImageRef of the main view bitmap content, and then 
// release that bitmap context 
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext); 
CGContextRelease(mainViewContentContext); 

// convert the finished resized image to a UIImage 
UIImage *theImage = [UIImage imageWithCGImage:mainViewContentBitmapContext]; 
// image is retained by the property setting above, so we can 
// release the original 
CGImageRelease(mainViewContentBitmapContext); 

// return the image 
return theImage; 
+1

Me ayudó mucho. ¿Podría agregar el encabezado y el pie de página de la función para completarlo? – Eden

+0

¿Qué es thumbnailPoint.x exactamente? @catlan –

+0

@ Reza.Ab lo siento, no recuerdo. escala * también se ve raro 9 años después. Supongo que en la mayoría de los casos la máscara es rect y la imagen rect debe ser la misma. Pruébalo y cuéntanos qué encuentras, – catlan

1

La imagen a ser enmascarado deben crearse con un canal alfa. El canal Alpha no puede ser creado a partir del código.

4
- (UIImage*) maskImage:(UIImage *)image { 

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

    UIImage *maskImage = [UIImage imageNamed:@"MaskFinal.png"]; 
    CGImageRef maskImageRef = [maskImage CGImage]; 

    // create a bitmap graphics context the size of the image 
    CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast); 


    if (mainViewContentContext==NULL) 
     return NULL; 

    CGFloat ratio = 0; 

    ratio = maskImage.size.width/ image.size.width; 

    if(ratio * image.size.height < maskImage.size.height) { 
     ratio = maskImage.size.height/ image.size.height; 
    } 

    CGRect rect1 = {{0, 0}, {maskImage.size.width, maskImage.size.height}}; 
    CGRect rect2 = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}}; 


    CGContextClipToMask(mainViewContentContext, rect1, maskImageRef); 
    CGContextDrawImage(mainViewContentContext, rect2, image.CGImage); 


    // Create CGImageRef of the main view bitmap content, and then 
    // release that bitmap context 
    CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext); 
    CGContextRelease(mainViewContentContext); 

    UIImage *theImage = [UIImage imageWithCGImage:newImage]; 

    CGImageRelease(newImage); 

    // return the image 
    return theImage; 
} 
+0

No funciona realmente ... –

Cuestiones relacionadas