您的当前位置:首页正文

内存优化之图片加载

来源:要发发知识网

基本大部分App中有一大批的图片资源文件,当这些图片加载到内存中后会占用相当大一部分内存。因此对内存的优化一方面可以从图片入手。


图片加载方式我工作用到的大概有三种:

  • 通过图片名加载: [UIImage imageNamed:@"图片名"]
  • 通过图片路径加载: [UIImage imageWithContentsOfFile:@"图片资源路径"];
  • 通过矢量图来加载:IconFont

图片名VS图片路径

图片资源来自于我曾经的东家-大彩

    //图片资源包路径
    NSString *accountPath =[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"MYFResouse.bundle/Account"];
    //图片名数组
    NSArray *imageNames = @[@"aboutBack",@"aboutLogo",@"account_wave",@"activeIcon",@"addbank",@"bg_yew",@"bigpeople",@"bottomLine",@"checked",@"closePassword"];
    //我创建30个imageView,循环加载图片
    for (NSInteger index = 0; index < 30; index++) {

        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40+66*(index%4),20+ 66*(index/4), 44, 44)];
        imageView.backgroundColor = [UIColor redColor];
        //方案一:根据图片路径加载图片
        NSString *imagePath = [accountPath stringByAppendingPathComponent:imageNames[index%imageNames.count]];
        imageView.image = [UIImage imageWithContentsOfFile:imagePath];
        //方案二:根据图片名加载图片
        imageView.image = [UIImage imageNamed:imageNames[index%imageNames.count]];
        [self.view addSubview:imageView];
    }

效果图:

Paste_Image.png
内存使用比较: Paste_Image.png

使用矢量图加载图片-iconFont

iconFont文件的来自于我现在的东家-融途

#import "ViewController.h"
#import "UIImage+Addation.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *iconFontNames = @[@"\U0000E649",@"\U0000E647",@"\U0000E63E",@"\U0000E644",@"\U0000E642",@"\U0000E646",@"\U0000E64A"];
    //我创建30个imageView,循环加载图片
    for (NSInteger index = 0; index < 30; index++) {

        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40+66*(index%4),20+ 66*(index/4), 44, 44)];
        //方案三: 矢量图
        NSString *iconName = iconFontNames[index%iconFontNames.count];
        imageView.image = [self imageWithIconFontName:iconName andFontSize:CGSizeMake(44, 44) andFontColor:[UIColor redColor]];
        [self.view addSubview:imageView];
    }
}

- (UIImage *)imageWithIconFontName:(NSString *)name andFontSize:(CGSize)size andFontColor:(UIColor *)color{
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    UILabel *imgaeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    UIFont *iconfont = [UIFont fontWithName:@"iconfont" size:size.height];
    imgaeLabel.font = iconfont;
    imgaeLabel.text = name;
    [imgaeLabel.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    return image;
}
@end

效果

Paste_Image.png
内存占用情况 Paste_Image.png