iOS中的图片使用方式、内存对比和最佳实践(来自苹果的最佳实践)

  • 前文摘要:https://juejin.im/post/5b2ddfa7e51d4553156be305
    以下为Objective-C方法:
- (UIImage *)loadSample:(NSURL *)filePathUrl size:(CGSize)pointSize scale:(long)scale {
    CGImageRef thumbnailImage;
    CGImageSourceRef imageSource;
    CFDictionaryRef imageOptions;
    CFDictionaryRef sourceOpt;
    CFStringRef imageKeys[4];
    CFTypeRef imageValues[4];
    
    CFStringRef imageKey[1];
    CFTypeRef imageValue[1];
    
    CFNumberRef thumbnailSize;
    imageKey[0] = kCGImageSourceShouldCache;
    imageValue[0] = (CFTypeRef)kCFBooleanFalse;
    sourceOpt = CFDictionaryCreate(NULL, (const void **)imageKey, (const void **)imageValue, 1,&kCFTypeDictionaryKeyCallBacks,&kCFTypeDictionaryValueCallBacks);
    
    //先判断数据是否存在
    imageSource = CGImageSourceCreateWithURL((CFURLRef)filePathUrl, sourceOpt);
    
    if (imageSource == NULL) {
        fprintf(stderr, "Image source is NULL.");
        return  NULL;
    }
    //创建缩略图等比缩放大小,会根据长宽值比较大的作为imageSize进行缩放
    NSInteger maxDimension = MAX(pointSize.width, pointSize.height) * scale;
    thumbnailSize = (__bridge CFNumberRef) @(maxDimension);
    
    imageKeys[0] = kCGImageSourceCreateThumbnailFromImageAlways;
    imageValues[0] = (CFTypeRef)kCFBooleanTrue;
    
    imageKeys[1] = kCGImageSourceShouldCacheImmediately;
    imageValues[1] = (CFTypeRef)kCFBooleanTrue;
    
    imageKeys[2] = kCGImageSourceCreateThumbnailWithTransform;
    imageValues[2] = (CFTypeRef)kCFBooleanTrue;
    
    //缩放键值对
    imageKeys[3] = kCGImageSourceThumbnailMaxPixelSize;
    imageValues[3] = (CFTypeRef)thumbnailSize;
    
    imageOptions = CFDictionaryCreate(NULL, (const void **) imageKeys,
                                      (const void **) imageValues, 4,
                                      &kCFTypeDictionaryKeyCallBacks,
                                      &kCFTypeDictionaryValueCallBacks);
    //获取缩略图
    thumbnailImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, imageOptions);
    UIImage *image = [UIImage imageWithCGImage:thumbnailImage];
    CFRelease(imageOptions);
    CFRelease(sourceOpt);
    CFRelease(thumbnailSize);
    CFRelease(imageSource);
    
    return image;

}

你可能感兴趣的:(iOS中的图片使用方式、内存对比和最佳实践(来自苹果的最佳实践))