我想从UIView创建一个UI
Image对象.视图不透明.
因为我正在使用以下代码:
因为我正在使用以下代码:
+ (UIImage *) imageWithView:(UIView *)view { UIGraphicsBeginImageContextWithOptions(view.bounds.size,view.opaque,[[UIScreen mainScreen] scale]); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage * img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; }
但由于某些原因,而不是透明的背景,我得到一个黑色背景的图像.
我已经尝试将UIGraphicsBeginImageContextWithOptions中的“opaque”参数设置为NO,但没有不同的结果.
任何建议?
(类似的问题CGContext transparency problem没有答案)
解决方法
我确定你创建这样的UIImage时不能定义透明度 – 你可以掩盖使用图像的UIImageView.
类似以下功能的类似操作可以实现:
// handles img masking operation CGImageRef CopyImageAndAddAlphaChannel(CGImageRef sourceImage) { CGImageRef retVal = NULL; size_t width = CGImageGetWidth(sourceImage); size_t height = CGImageGetHeight(sourceImage); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef offscreenContext = CGBitmapContextCreate(NULL,width,height,8,colorSpace,kCGImageAlphaPremultipliedFirst); if (offscreenContext != NULL) { CGContextDrawImage(offscreenContext,CGRectMake(0,height),sourceImage); retVal = CGBitmapContextCreateImage(offscreenContext); CGContextRelease(offscreenContext); } CGColorSpaceRelease(colorSpace); return retVal; } // png masks can mask png,gif or jpg... - (UIImage*)maskImage:(UIImage *)image withMask:(UIImage *)maskImage { CGImageRef maskRef = maskImage.CGImage; CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),CGImageGetHeight(maskRef),CGImageGetBitsPerComponent(maskRef),CGImageGetBitsPerPixel(maskRef),CGImageGetBytesPerRow(maskRef),CGImageGetDataProvider(maskRef),NULL,false); CGImageRef sourceImage = [image CGImage]; CGImageRef imageWithAlpha = sourceImage; //add alpha channel for images that don't have one (ie GIF,JPEG,etc...) //this however has a computational cost if ((CGImageGetAlphaInfo(sourceImage) == kCGImageAlphaNone) || (CGImageGetAlphaInfo(sourceImage) == kCGImageAlphaNoneSkipFirst)) { imageWithAlpha = CopyImageAndAddAlphaChannel(sourceImage); } CGImageRef masked = CGImageCreateWithMask(imageWithAlpha,mask); CGImageRelease(mask); //release imageWithAlpha if it was created by CopyImageAndAddAlphaChannel if (sourceImage != imageWithAlpha) { CGImageRelease(imageWithAlpha); } UIImage* retImage = [UIImage imageWithCGImage:masked]; CGImageRelease(masked); return retImage; }
你可以这样称呼:
UIImage *imgMasked = [self maskImage:[UIImage imageNamed:@"full_image.png"] withMask:[UIImage imageNamed:@"masked_image.png"]];
masked_image.png需要是一个alpha通道的图像,它将剪出你的黑色bg.