imageWithContentofFile 封装图片

-(id) init {

    self = [super init];

    if (self) {

        CGRect rect_screen = [[UIScreen mainScreen]bounds];

        CGSize size_screen = rect_screen.size;

        CGFloat scale_screen = [UIScreen mainScreen].scale;

        size_screen.width *= scale_screen;

        size_screen.height *= scale_screen;

        if (   CGSizeEqualToSize(size_screen, CGSizeMake(320, 480))

            || CGSizeEqualToSize(size_screen, CGSizeMake(480, 320))

            || CGSizeEqualToSize(size_screen, CGSizeMake(1024, 768))

            || CGSizeEqualToSize(size_screen, CGSizeMake(768, 1024))) {

            isRetain = NO;             

        } else {

            isRetain = YES;

        }

        imageDictionary = [[NSMutableDictionary alloc] initWithCapacity:10];

        [self performSelector:@selector(runPerTimes) withObject:nil afterDelay:KAutoReleaseTime]; // 60 秒后释放缓存

    }

    

    return self;

}


-(void) dealloc{

    if (imageDictionary) {

        [imageDictionary release];

        imageDictionary = nil;

    }

    [super dealloc];

}


- (UIImage *)imageNamed:(NSString *)name{

    NSMutableString* temp = [[NSMutableString alloc] initWithString:name];

    NSRange range = [temp rangeOfString:@"@2x"];

    if (range.length > 0 && !isRetain) {//低分辨率下有@2x

        [temp deleteCharactersInRange:range];

    } else if(range.length == 0 && isRetain){//高分辨率下无@2x

        range = [temp rangeOfString:@"."];

        if (range.length == 0) {

            [temp appendString:@"@2x"];

        } else {

            [temp insertString:@"@2x" atIndex:range.location];

        }

    }

    range = [temp rangeOfString:@"."];//没有后缀

    if (range.length == 0) {

        [temp appendString:@".png"];

    }

    UIImage* image = [imageDictionary objectForKey:temp];

    if (image == nil) {

        NSString *path = [NSString stringWithFormat:@"%@/%@",

                          [[NSBundle mainBundle] bundlePath],

                          temp];

        image = [[UIImage alloc] initWithContentsOfFile:path];

        if (image) {

            [imageDictionary setObject:image forKey:temp];

            [image release];

        }

    }


    [temp release];

    return image;

}


-(void) runPerTimes{

    [self releaseNotUsedImages];

    [self performSelector:@selector(runPerTimes) withObject:nil afterDelay:KAutoReleaseTime];

}


- (void) releaseNotUsedImages{

    NSArray* array = [imageDictionary allKeys];

    for (int i = 0; i < [array count]; i++) {

        NSString* name = [array objectAtIndex:i];

        UIImage* image = [imageDictionary objectForKey:name];

        if (image.retainCount <= 1) {

            [imageDictionary removeObjectForKey:name];

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值