After changing image size, image's transparent

2020-05-01 09:17发布

问题:

I am trying to change image size according to my view so I wrote this code for that.

 -(UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a bitmap context.
    UIGraphicsBeginImageContextWithOptions(newSize, YES, [UIScreen mainScreen].scale);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    NSData *imageData = UIImagePNGRepresentation(newImage);
    UIGraphicsEndImageContext();


    UIImage *img=[UIImage imageWithData:imageData];

    return img;

}

It's working fine, but when I get the image, its transparent part becomes in black, maybe it's converting it into jpg. I used a PNG image. Any ideas? Thanks in advance.

回答1:

You should use NO as the second argument, that toggles the transparency of the image.

UIGraphicsBeginImageContextWithOptions(newSize, NO, [UIScreen mainScreen].scale);

Check out Apple's documentation for more details.



回答2:

With refernce to https://developer.apple.com/documentation/uikit/1623912-uigraphicsbeginimagecontextwitho?language=objc

Method:

void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);

Where opaque is

opaque A Boolean flag indicating whether the bitmap is opaque. If you know the bitmap is fully opaque, specify YES to ignore the alpha channel and optimize the bitmap’s storage. Specifying NO means that the bitmap must include an alpha channel to handle any partially transparent pixels.

You use this function to configure the drawing environment for rendering into a bitmap. The format for the bitmap is a ARGB 32-bit integer pixel format using host-byte order. If the opaque parameter is YES, the alpha channel is ignored and the bitmap is treated as fully opaque ( kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host ). Otherwise, each pixel uses a premultipled ARGB format ( kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host ).

You should put opaque to NO in your case for transparent image