【问题标题】:Image is not being shown when using UIImage imageWithData:NSData dataWithContentsOfFile使用 UIImage imageWithData:NSData dataWithContentsOfFile 时不显示图像
【发布时间】:2012-07-04 13:36:45
【问题描述】:

下面的代码没有显示从网上下载并写入我的应用程序文档目录的图像。 我检查了iphone的模拟器文件目录里面,下载的文件是存在的。 但图像不显示。

当尝试使用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];
}

【问题讨论】:

标签: iphone ios ios4 uiimageview


【解决方案1】:

试试这个,这对我来说非常有用:

 - (void)viewDidLoad
{
     [super viewDidLoad];

     NSURL *url1 = [NSURL URLWithString:@"http://mobiledevelopertips.com/images/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];

    }
}

【讨论】:

    【解决方案2】:

    您可以使用

    ,而不是先将文件转换为NSData

    [UIImage imageWithContentsOfFile:filePath]

    直接加载具有给定路径的image

    【讨论】:

      猜你喜欢
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多