简体   繁体   中英

How to add a jpg or png image to an UIImage and then display in a UIImageView?

UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"contactHeader.png"];
_headersView = [[UIImageView alloc] initWithImage:img];

I have already hooked up the connections for the UIImageView (_headersView) in IB. The image I want to load is in my project tree structure as well.

Am I creating the UIImage the right way?

If the file is in your bundle you can just use

UIImage *img = [UIImage imageNamed:@"contactHeader"];
_headersView = [[UIImageView alloc] initWithImage:img];

If the image is in your documents directory you can use

// 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;

try this

-(NSString *)getPath:(NSString *)filename
{
self.path = [[NSBundle mainBundle]pathForResource:filename ofType:@"png"];
return path;
path = nil;
}

self.youImageView.image = [UIImage imageWithContentsOfFile:[self getPath:@"123"]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM