【问题标题】:adding an image to Imageview from Document folder Not loading从 Document 文件夹将图像添加到 Imageview 未加载
【发布时间】:2012-11-15 06:55:55
【问题描述】:

我正在尝试解决相当简单的问题一段时间,但没有成功。我正在将文件保存到设备上的 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];
    }
}

【问题讨论】:

    标签: objective-c ios image ipad


    【解决方案1】:

    你的代码有问题。

    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];
        }
    }
    

    【讨论】:

      【解决方案2】:

      更改代码:

      UIImage *theImage = [UIImage imageWithContentsOfFile:outputPath];
      
      if (theImage)
      {
          display = [UIImageView alloc]  initWithImage:theImage];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-24
        相关资源
        最近更新 更多