为图片添加透明度

- (UIImage *)applyAlpha:(CGFloat)alpha
{
    int bmpAlpha = MIN(255, MAX(0, (255*alpha)));
    UIImage *image;
    int width = self.size.width * self.scale;
    int height = self.size.height * self.scale;
    
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    if (colorspace == NULL) {
        ATLog(@"Create Colorspace Error!");
        return nil;
    }
    
    Byte *imgData = NULL;
    imgData = malloc(width * height * 4);
    if (imgData == NULL) {
        ATLog(@"Memory Error!");
        CGColorSpaceRelease(colorspace);
        return nil;
    }
    
    CGContextRef bmpContext = CGBitmapContextCreate(imgData, width, height, 8, width * 4, colorspace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
    if (!bmpContext) {
        ATLog(@"Create Bitmap context Error!");
        CGColorSpaceRelease(colorspace);
        return nil;
    }
    
    CGContextDrawImage(bmpContext, CGRectMake(0, 0, width, height), self.CGImage);
    for (long i = 0; i < width * height; i++) {
        imgData[4*i+3] = bmpAlpha;
    }
    
    CGImageRef imageRef = CGBitmapContextCreateImage(bmpContext);
    if (imageRef != NULL) {
        image = [[UIImage alloc] initWithCGImage:imageRef];
        CGImageRelease(imageRef);
    }
    
    CGColorSpaceRelease(colorspace);
    CGContextRelease(bmpContext);
    free(imgData);
    
    return image;
}

UIimage添加分类,改变图片透明度alpha:0.0 ~1.0 .

你可能感兴趣的:(为图片添加透明度)