从Document文件夹向Imageview添加图像未加载

时间:2012-11-27 15:47:07

标签: objective-c ios image ipad

我试图在一段时间内找到相当简单的问题而现在没有成功。我将文件保存到设备上的Documents目录,并尝试稍后使用图像视图加载它。我确认该文件实际上存在。为什么我的图像没有显示?

提前感谢您的帮助。

以下是我尝试将图像加载到ImageView中的代码:

 -(void)loadFileFromDocumentFolder:(NSString *) filename
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *outputPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString: filename] ];

    NSLog(@"outputPath: %@", outputPath);
    UIImage *theImage = [UIImage new];
    [UIImage imageWithContentsOfFile:outputPath];

    if (theImage)
    {
        display = [UIImageView new];
        display = [display initWithImage:theImage];

        [self.view addSubview:display];
    }
}

2 个答案:

答案 0 :(得分:3)

你的代码有些问题。

UIImage *theImage = [UIImage new];

在此行中,您可以创建一个新的UIImage对象,但不对其执行任何操作。

[UIImage imageWithContentsOfFile:outputPath]

此类方法将返回一个UIImage对象,其中包含来自文件的图像加载。

您使用UIImageView执行相同的操作。

NSString *outputPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString: filename] ];

此外,您不需要[NSString stringWithString: filename]只需创建一个不需要的额外字符串,因为filename已经是字符串。

您的代码应该像这样:

 -(void)loadFileFromDocumentFolder:(NSString *) filename {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *outputPath = [documentsDirectory stringByAppendingPathComponent:filename ];

    NSLog(@"outputPath: %@", outputPath);
    UIImage *theImage = [UIImage imageWithContentsOfFile:outputPath];

    if (theImage) {
        display = [[UIImageView alloc] initWithImage:theImage];
        [self.view addSubview:display];
    }
}

答案 1 :(得分:0)

chang代码:

UIImage *theImage = [UIImage imageWithContentsOfFile:outputPath];

if (theImage)
{
    display = [UIImageView alloc]  initWithImage:theImage];
}
相关问题