我有一个图像(.png文件)要放置在ViewController的ImageView中。我使用以下代码,但是模拟器为我提供了没有图像的空白白色视图。 .png文件与ViewController文件位于同一目录中。这是代码:

@implementation ViewController
{
    NSArray *_pArray;
    UIImage *_image;
    UIImageView *_imageView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _image = [[UIImage alloc] initWithContentsOfFile:@"TM-1P2.png"];
    _imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    [_imageView setImage:_image];
    [_imageView setContentMode:UIViewContentModeScaleAspectFit];
    [self.view addSubview:_imageView];
}

最佳答案

如果检查_image(在NSLog或在调试器中),则可能是nil。使用initWithContentsOfFile,您应该指定整个路径,例如:

NSString *path = [[NSBundle mainBundle] pathForResource:@"TM-1P2" ofType:@"png"];
_image = [[UIImage alloc] initWithContentsOfFile:path];

或者,您可以使用以下命令,该命令会自动在分发包中查找图像:
_image = [UIImage imageNamed:@"TM-1P2.png"];

后一种语法imageNamed缓存图像(即即使您关闭视图控制器也将其保留在内存中)。如果您必须在整个应用程序中一次又一次地使用同一张图片(因为不必每次都重新加载它),那就太好了,但是如果只使用一次,则可能不想使用imageNamed。正如imageNamed文档所说:

如果您有只显示一次的图像文件,并且希望确保不会将其添加到系统的缓存中,则应该使用imageWithContentsOfFile:创建图像。这会将您的一次性图像排除在系统图像缓存之外,从而有可能改善应用程序的内存使用特性。

请注意,这两个都假设您已成功将此图像添加到捆绑包中。

另一方面,如果图像在您的Documents文件夹中,则可以这样加载:
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentsPath stringByAppendingPathComponent:@"TM-1P2.png"];
_image = [[UIImage alloc] initWithContentsOfFile:path];

最后,请注意,iOS设备区分大小写(通常模拟器不区分大小写),因此请确保大写正确。

与您的问题无关,括号之间的那些变量可能不应该在@implementation中定义,而应该将它们放在@interface中。例如,可以将它们放在.h文件中,或者更好的是,可以将它们放在.m文件的 private 类扩展中,就在@implementation之前:
@interface ViewController ()
{
    NSArray *_pArray;
    UIImage *_image;
    UIImageView *_imageView;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"TM-1P2" ofType:@"png"];
    _image = [[UIImage alloc] initWithContentsOfFile:path];
    _imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    [_imageView setImage:_image];
    [_imageView setContentMode:UIViewContentModeScaleAspectFit];
    [self.view addSubview:_imageView];
}

// ...

@end

关于ios - 以编程方式将图像放置在UIViewController上的UIImageView中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21615406/

10-09 18:17
查看更多