首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将imageNamed转换为imageWithContentsOfFile:

将imageNamed转换为imageWithContentsOfFile:
EN

Stack Overflow用户
提问于 2014-02-17 06:48:55
回答 2查看 537关注 0票数 0

我的图像代码是

代码语言:javascript
复制
-(IBAction)start:(id)sender
{
    animation.animationImages = [NSArray arrayWithObjects:
                                 [UIImage imageNamed:@"Paddle 1.png"],
                                 [UIImage imageNamed:@"Paddle 2.png"],
                                 [UIImage imageNamed:@"Paddle 3.png"],
                                 [UIImage imageNamed:@"Paddle 4.png"],
nil];
    [animation setAnimationRepeatCount:0];
    animation.animationDuration = 2.5;
    [animation startAnimating];
}

这是缓存太多的内存,我在前面的一个问题中被告知要将我的代码交换为

代码语言:javascript
复制
[UIImage imageWithContentsOfFile: GetImgWithoutCaching(@"Paddle 1.jpg")]

代码语言:javascript
复制
UIImage* GetImgWithoutCaching(NSString* imgName)
{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:imgName ofType:nil];
    return [UIImage imageWithContentsOfFile:imagePath];
}

编写代码的正确方法是什么?我是否将该代码按原样放置在我的.m中?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-17 07:41:43

首先,您应该检查是否使用视网膜图片:

代码语言:javascript
复制
BOOL isHighResolution = NO;
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    if ([UIScreen mainScreen].scale > 1) {
        isHighResolution = YES;
    }
}

如果您使用的是视网膜图片,请在图像名称中添加@2x,如下所示:

代码语言:javascript
复制
NSString *noExtFileName = [name stringByDeletingPathExtension];
if (isHighResolution) {
    if (![noExtFileName hasSuffix:@"@2x"]) {
       noExtFileName = [noExtFileName stringByAppendingString:@"@2x"];
    }
}

 //if image only "png" type
return [[NSBundle mainBundle] pathForResource:noExtFileName ofType:@"png"];
票数 1
EN

Stack Overflow用户

发布于 2014-02-17 06:50:55

由于GetImgWithoutCaching函数返回需要的UIImage:

代码语言:javascript
复制
-(IBAction)start:(id)sender
{
    animation.animationImages = [NSArray arrayWithObjects:
                                 GetImgWithoutCaching(@"Paddle 1.jpg"),
                                 GetImgWithoutCaching(@"Paddle 2.jpg"),
                                 GetImgWithoutCaching(@"Paddle 3.jpg"),
                                 GetImgWithoutCaching(@"Paddle 4.jpg"),
nil];
    [animation setAnimationRepeatCount:0];
    animation.animationDuration = 2.5;
    [animation startAnimating];
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21822520

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档