Tôi khá chắc chắn rằng bạn không thể định nghĩa một sự minh bạch khi tạo UIImages như thế này - bạn có thể che giấu UIImageView của bạn mà sử dụng hình ảnh mặc dù.
Something như các chức năng sau cho phép cho loại hình này hoạt động:
// 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, 0, colorSpace, kCGImageAlphaPremultipliedFirst);
if (offscreenContext != NULL) {
CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, 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;
}
Bạn hơn có thể gọi nó như thế này:
UIImage *imgMasked = [self maskImage:[UIImage imageNamed:@"full_image.png"] withMask:[UIImage imageNamed:@"masked_image.png"]];
masked_image.png cần phải được một hình ảnh chuyển alpha mà sẽ cắt bỏ bg đen của bạn.
bạn có thể vui lòng cho tôi biết thêm chi tiết những gì bạn có ý nghĩa bởi "mặt nạ xem hình ảnh của tôi"? Và nó sẽ hoàn thành những gì tôi đang cố gắng để đạt được? –
có thể sử dụng hình ảnh gif làm mặt nạ hình ảnh không? – Dhruv
@Lemonsanver: CopyImageAndAddAlphaChannel Tôi nhận biểu tượng này là biểu tượng không xác định .. Vui lòng cho tôi biết những gì có thể làm ngay bây giờ – Seeker