在UIImageView中显示本地图片

22

如何在UIImageView组件中显示来自硬盘的图像?

我有一个名为“images”的本地文件夹,希望通过相对路径访问它,因为我想将这些图像与应用程序一起打包。

4个回答

59

要从电脑上的某个位置加载图像,请使用:

UIImage * myImage = [UIImage imageWithContentsOfFile: @"../images/1.png"];

或者将图片添加到Xcode项目中并使用:

UIImage * myImage = [UIImage imageNamed: @"1.png"];

接着将图片添加到 ImageView 中:

UIImageView * myImageView = [[UIImageView alloc] initWithImage: myImage];

2
由于您想将其与应用程序捆绑在一起,因此应使用此处的最后两行代码,而不是顶部的代码。您还应该将该图像从硬盘拖到项目中的文件夹(例如资源文件夹)中。 - tazboy

9

只要图片在资源文件夹中,您无需提供任何路径。

您可以使用以下方法在imageView中显示该图像。

yourImageView.image = [UIImage imageNamed:@"something.png"];

你觉得使用这种方法不需要加文件扩展名吗? - zonabi

2
UIImage *img = [UIImage imageWithContentsOfFile:(the file path)];
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];

查看imageWithContentsOfFile:文档。


0

硬盘中的图像是什么意思?您是说您将图像保存在 iPhone 应用程序的捆绑包中吗?如果是这样,您可以像这样创建这些图像的数组...

NSMutableArray *imageArray;
imageArray=[[NSMutableArray alloc]initWithObjects:@"001.jpg",@"002.jpg",@"003.jpg",@"004.jpg",nil];

然后可以通过这个数组访问您的图像;

或者,如果您只想从捆绑包中显示单个图像,可以这样做

UIImageView *creditCardImageView=[[UIImageView alloc]initWithFrame:CGRectMake(10, 16, 302, 77)];
    creditCardImageView.image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"CreditCard_2RowTable" ofType:@"png"]];
    [self.view addSubview:creditCardImageView];

这会对你有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接