如何将jpg或png图像添加到UIImage然后在UIImageView中显示?

3 image uiimageview uiimage

UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"contactHeader.png"];
_headersView = [[UIImageView alloc] initWithImage:img];
Run Code Online (Sandbox Code Playgroud)

我已经在IB中连接了UIImageView(_headersView)的连接.我想加载的图像也在我的项目树结构中.

我是以正确的方式创造UIImage吗?

Pau*_*l.s 8

如果文件在您的包中,您可以使用

UIImage *img = [UIImage imageNamed:@"contactHeader"];
_headersView = [[UIImageView alloc] initWithImage:img];
Run Code Online (Sandbox Code Playgroud)

如果图像位于文档目录中,则可以使用

// Get the path to your documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

// Add the file to the end of the documents path
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"contactHeader.png"];

UIImage *img = [[UIImage alloc] imageWithContentsOfFile:filePath];
_headersView = [[UIImageView alloc] initWithImage:img];
[img release]; img = nil;
Run Code Online (Sandbox Code Playgroud)