且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UIImageWriteToSavedPhotosAlbum保存为PNG透明度?

更新时间:2022-11-19 10:07:13

这是我之前注意到的问题,并在 Apple开发者论坛大约一年前。据我所知,它仍然是一个悬而未决的问题。

This is a problem I have noticed before and reported on the Apple Developer Forums about a year ago. As far as I know it is still an open issue.

如果您有时间,请花时间在 Apple Bug报告。如果有更多人报告此问题,Apple更有可能会修复此方法以输出无损,支持Alpha的PNG。

If you have a moment, please take the time to file a feature request at Apple Bug Report. If more people report this issue, it is more likely that Apple will fix this method to output non-lossy, alpha-capable PNG.

EDIT

如果您可以在内存中撰写图像,我认为以下内容可以起作用或者至少可以帮助您开始:

If you can compose your image in memory, I think something like the following would work or at least get you started:

- (UIImage *) composeImageWithWidth:(NSInteger)_width andHeight:(NSInteger)_height {
    CGSize _size = CGSizeMake(_width, _height);
    UIGraphicsBeginImageContext(_size);

    // Draw image with Quartz 2D routines over here...

    UIImage *_compositeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return _compositeImage;
}

//
// cf. https://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/FilesandNetworking/FilesandNetworking.html#//apple_ref/doc/uid/TP40007072-CH21-SW20
//

- (BOOL) writeApplicationData:(NSData *)data toFile:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    if (!documentsDirectory) {
        NSLog(@"Documents directory not found!");
        return NO;
    }
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    return ([data writeToFile:appFile atomically:YES]);
}

// ...

NSString *_imageName = @"myImageName.png";
NSData *_imageData = [NSData dataWithData:UIImagePNGRepresentation([self composeImageWithWidth:100 andHeight:100)];

if (![self writeApplicationData:_imageData toFile:_imageName]) {
    NSLog(@"Save failed!");
}