iOS 中只用3x图片解决方案(附源码)

随着Apple推出了6plus,图片资源成了一大问题,2x-640x960 2x-750x1334 3x-1242x2208,各种规格的图片,安装包必然增大了不少,那么多种类的图片难免会漏掉一些,所以自己写了一个UIImage的Category库,只需要在Bundle中添加3x的图片即可实现6plus使用3x图片,6及以下版本使用2x图片。

话不多说,详情见代码和使用方式

(如果有问题请直接回复,歇歇)

//
//  UIImage+Compress.h
//  ImageCompress
//
//  Created by Hunk on 15/3/3.
//  Copyright (c) 2015年 Hunk. All rights reserved.
//
//  图片压缩,bundle中只需要存在@3x.png的图片,@2x.png的图片会根据需要自动生成到Sandbox中

#import <UIKit/UIKit.h>

/* 使用方式
 *
 * logo_huodong     :bundle中后缀为@3x.png的图片名字,使用时无需加入任何后缀,直接传入名字即可
 * imageWithName    : 为UIImage的Category方法
 *
 * UIImage *image = [UIImage imageWithName:@"logo_huodong"];
 * UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((CGRectGetWidth(self.view.bounds) - image.size.width) / 2.0, 50.0, image.size.width, image.size.height)];
 * [imageView setImage:image];
 * [self.view addSubview:imageView];
*/


@interface UIImage (Compress)

/**
 *  Get image with image name
 *
 *  @param name : Image name. A image named "[email protected]", inputing "logo" is necessary.
 *
 *  @return UIImage
 */
+ (UIImage *)imageWithName:(NSString *)name;

@end

//
//  UIImage+Compress.m
//  ImageCompress
//
//  Created by Hunk on 15/3/3.
//  Copyright (c) 2015年 Hunk. All rights reserved.
//

#import "UIImage+Compress.h"

#define BASE_IMG_WIDTH  (1242)
#define BASE_IMG_HEIGHT (2208)

#define SUFFIX_3X_PNG   @"@3x.png"
#define SUFFIX_2X_PNG   @"@2x.png"

@implementation UIImage (Compress)

// 获取图片
+ (UIImage *)imageWithName:(NSString *)name
{
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        return [UIImage imageNamed:name];
    }
    else
    {
        NSAssert(NO == [name hasSuffix:SUFFIX_3X_PNG], @"File name suffix @3x.png is unnecessary!");
        
        NSString *srcImgName = [name stringByAppendingString:SUFFIX_3X_PNG];
        
        NSString *desImgName = [UIImage desImageName:[UIImage getImageName:name] withExt:SUFFIX_2X_PNG];
        
        // Path
        NSString *cacheDir = [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Caches/Resources/images/"];
        
        // 判断存放图片的文件夹是否存在,不存在则创建对应文件夹
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        BOOL isDir = NO;
        BOOL isDirExist = [fileManager fileExistsAtPath:cacheDir isDirectory:&isDir];
        if(!(isDirExist && isDir))
        {
            NSError *error = nil;
            BOOL bCreateDir = [fileManager createDirectoryAtPath:cacheDir withIntermediateDirectories:YES attributes:nil error:&error];
            
            if(!bCreateDir)
            {
                NSLog(@"Create Directory Failed! : %@", error.description);
                
                return nil;
            }
        }
        
        NSString *desPath = [cacheDir stringByAppendingPathComponent:desImgName];
        
        UIImage *desImage = [UIImage imageWithContentsOfFile:desPath];
        
        if(!desImage)
        {
            // 如果从Cache中没有取到图片
            if([UIImage compressImage:srcImgName compressionQuality:0.8 desPath:desPath])
            {
                // 压缩成功
                desImage = [UIImage imageWithContentsOfFile:desPath];
            }
            else
            {
                desImage = nil;
            }
        }
        
        return desImage;
    }
}

// 压缩图片
+ (BOOL)compressImage:(NSString *)name compressionQuality:(CGFloat)compressionQuality desPath:(NSString *)desPath
{
    if(name == nil || desPath == nil)
    {
        return NO;
    }
    
    UIImage *srcImage = [UIImage imageNamed:name];
    
    if(srcImage == nil)
    {
        return NO;
    }
    
    // 根据屏幕尺寸设置图片尺寸
    UIScreen *mainScreen = [UIScreen mainScreen];

    // Default is Portrait or PortraitUpsideDown
    CGSize baseImgSize = CGSizeMake(BASE_IMG_WIDTH, BASE_IMG_HEIGHT);
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    if(orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight)
    {
        // LandscapeLeft or LandscapeRight
        baseImgSize = CGSizeMake(BASE_IMG_HEIGHT, BASE_IMG_WIDTH);
    }
    
    CGSize newSize = CGSizeMake(srcImage.size.width * srcImage.scale * (CGRectGetWidth(mainScreen.bounds) * mainScreen.scale) / baseImgSize.width, srcImage.size.height * srcImage.scale * (CGRectGetHeight(mainScreen.bounds) * mainScreen.scale) / baseImgSize.height);
    
    // Reset image
    UIImage *newImage = [UIImage imageWithImage:srcImage scaleToSize:newSize];
    
    // 对图片进行压缩
    NSData *imageData = UIImageJPEGRepresentation(newImage, compressionQuality);
    
    // 保存新图片
    return [imageData writeToFile:desPath atomically:YES];
}

// 重设图片的全名(带扩展名)
+ (NSString *)desImageName:(NSString *)srcImageName withExt:(NSString *)extName
{
    return [srcImageName stringByAppendingString:extName];
}

// 获取图片的名字(不带扩展名)
+ (NSString *)getImageName:(NSString *)srcImage
{
    if(srcImage)
    {
        NSArray *tempArray = [srcImage componentsSeparatedByString:@"."];
        
        if(tempArray)
        {
            // 有.分割的文件名
            if([tempArray count] > 1)
            {
                NSString *extName = [tempArray lastObject];
                
                // 严格判断文件的扩展名
                if([extName isEqualToString:@"png"] || [extName isEqualToString:@"jpg"] || [extName isEqualToString:@"jpeg"])
                {
                    return [srcImage substringWithRange:NSMakeRange(0, srcImage.length - (extName.length + 1))];
                }
                else
                {
                    return nil;
                }
            }
            else
            {
                return srcImage;
            }
        }
        else
        {
            return srcImage;
        }
    }
    return nil;
}

// 对图片尺寸进行重新设置
+ (UIImage *)imageWithImage:(UIImage*)image scaleToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    
    [image drawInRect:CGRectMake(0.0, 0.0, newSize.width, newSize.height)];
    
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

@end


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。