如何解决使用iOS从捆绑软件加载图像
| 我在项目中添加了一个装有一些图像的“ 0”文件夹。 引用此图像直接写类似这样的图像是否正确:[UIImage imageNamed:@\"imageInBundle.png\"];
哪种方法是访问和使用这些图像的最佳方法?
解决方法
没错,
imageNamed:
将搜索您的主捆绑包。项目中的图像,即使它们在项目导航器中位于不同的组中,也将位于您的主捆绑包中,并且可以通过名称直接访问。
,如果这样不起作用,请尝试
[UIImage imageNamed:@\"yourbundlefile.bundle/imageInBundle.png\"];
最好
,1)如果要使用捆绑软件,请转到捆绑软件目标并将COMBINE_HIDPI_IMAGES设置为NO。
在另一种情况下,图像将转换为tiff格式。
2)试试这段代码:
NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@\"YourBundle\" withExtension:@\"bundle\"]];
NSString *imagePath = [bundle pathForResource:@\"imageInBundle\" ofType:@\"png\"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
,值得庆幸的是,Apple从iOS 8开始为imageNamed:inBundle:compatibleWithTraitCollection:
提供了适当的API。
它的用法如下:
[UIImage imageNamed:@\"image-name\"
inBundle:[NSBundle bundleForClass:self.class]
compatibleWithTraitCollection:nil]
或迅速:
let image = UIImage(named: \"image-name\",inBundle: NSBundle(forClass: self),compatibleWithTraitCollection: nil)
,此方法在xcode项目中的任何地方返回图像:=>
+(UIImage*)returnImageFromResourceBundle:(NSString*)nameOfImage
{
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@\"Resource\" ofType:@\"bundle\"];
NSString *imageString = [[NSBundle bundleWithPath:bundlePath] pathForResource:nameOfImage ofType:@\"png\"];
UIImage *retrievedImage = [[UIImage alloc] initWithContentsOfFile: imageString];
return retrievedImage;
}
,迅捷3
let myImage = UIImage(named: \"nameOfImage\",in: Bundle(for: type(of: self)),compatibleWith: nil)
我无法获取当前的捆绑包,所以我这样做:
Bundle(for: type(of: self))
,由于我必须为Swift弄清楚这一点,所以我想还要添加...。
if let imagePath = NSBundle.mainBundle().pathForImageResource(\"TestImage.png\")
{
imageView.image = NSImage(contentsOfFile: imagePath)
}
捆绑包中Supporting Files
组中有TestImage.png
的位置。
,对于Swift 3
let prettyImage = UIImage(named: \"prettyImage\",in: Bundle(for: self),compatibleWith: nil)
,迅捷版
@AndrewMackenzie的答案对我没有帮助。这是起作用的
let image = UIImage(named: \"imageInBundle.png\")
imageView.image = image
我的完整答案在这里。
,如果要在同一viewController中多次使用它,一种快速的方法:
在与以下方法相同的类中的任意位置获取图像:
// this fetches the image from: MyBundle.bundle/folder/to/images/myImage.png
UIImage *myImage = [self imageFromBundle:@\"MyBundle\" withPath:@\"folder/to/images/myImage.png\"];
获取图像的方法:
- (UIImage *)imageFromBundle:(NSString *)bundleName withPath:(NSString *)imageName
{
NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:bundleName withExtension:@\"bundle\"];
NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
NSString *imagePath = [bundle pathForResource:imageName ofType:nil];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
return image;
}
或者直接将其称为捆绑软件:
UIImage *myImage = [UIImage imageNamed:@\"MyBundle.bundle/folder/to/images/myImage.png\"];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。