[英]How do I determine the path of the file that -[UIImage imageNamed:] will load?
我有一个带有一堆使用-[UIImage imageWithContentsOfFile:]
和完整路径的代码的继承项目。 我将其转换为使用-[UIImage imageNamed:]
和仅文件名(无扩展名),因此我可以将其传递给@"icon"
之类的东西,并获得icon.png
或icon@2x.png
或icon@2x.png
icon~ipad.png
,视情况而定。
问题是,程序中有一部分我想检查图像的大小,如果太大,我想显示TooBigImage.png
。
所以我需要知道,如果我调用[UIImage imageNamed: someName]
,它将使用哪个扩展名/修改名。 基本上,我想要该文件的路径,因此可以在加载图像之前检查其大小。
或者,如果有一种方法可以检查imageSizeForImageNamed:
或类似的方法,我可以使用它,但是我什么都不知道。
我宁愿不重新执行整个“如果视网膜,附加@ 2x等...”的事情,因为这(a)繁琐而(b)脆弱(如果Apple改变/增强了行为,该怎么办?)
提示?
谢谢!
对于像素,请使用size
和scale
属性:
UIImage *getMySize = [UIImage imageNamed:@"blah"];
float width = getMySize.scale * getMySize.size.width;
float height = getMySize.scale * getMySize.size.height;
这是UIImage文档 。
据我所知,您应该实现自己的功能来手动检查文件的大小。
您可以自己生成名称,例如:
-(bool)fileOk:(NSString*)filename
{
bool retina = [UIScreen mainScreen].scale == 2.0;
static bool iPad = UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad;
//Generate the filename
NSString *fullFilename = [NSString stringWithFormat:@"%@%@%@",filename,(retina)?@"@2x":@"",(iPad)?@"~ipad":@"~iphone"];
//Get the size:
NSError *error;
NSString *fullPath=[[NSBundle mainBundle] pathForResource:fullFilename ofType:@"png"];
NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath: fullPath error:&error];
return (fileDictionary && [fileDictionary fileSize]<SOME_TO_BIG_SIZE_CONSTANT);
}
然后,您可以选择是否要显示图像。 我没有尝试过代码,所以可能会有一些错别字...我希望这是您要查找的内容...
[UIImage imageNamed: @"icon"]
始终在应用程序主捆绑包中查找。 因此, icon.png
必须位于包中才能找到。 那里没有子路径。
但是,您可以使用[NSBundle bundleWithPath: @"subfolder"]
定义自己的捆绑包,这里的优点是您可以使用捆绑包方法检索优化的资产。
NSBundle *bundle = [[NSBundle bundleWithPath: @"folder"] autorelease];
然后, [bundle pathForResource:ofType:]
将从您的文件夹(即[bundle pathForResource:ofType:]
返回正确的图像资源路径,并且[UIImage imageWithContentsOfFile:]
将处理大小修饰符。
尽管这个问题没有答案,但它很好地总结了我退出的经历。 NSBundle pathForResource:ofType:和UIImage imageWithContentsOfFile:如何处理缩放比例和设备修饰符?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.