When programming in any language I find that there are always several things that no matter how hard I try to remember will never stick. One thing as of late has been using images within objective-c and iPhone development.
So many ways!
There are several ways to get images onto your display. The two I find I’m using the most are calling an image from the web, and using an image from your resource directory. Below are two snippets that I find useful to have within your snippet collection.
Snippet 1: Getting an image from the web
- The image link I’ll be using in the first example is: http://farm5.static.flickr.com/4098/4911106000_9c3a16bb59.jpg
// ----------------------- .h ------------------------
...
UIImageView *imgHolder;
...
@property(nonatomic, retain) IBOutlet UIImageView *imgHolder;
// ----------------------- .m ------------------------
// PART 1 - update url of path to the image
// PART 2 - update the variable reference to the UIImageView object
// -----------------------------------------------
// ===== PART 1 =====
NSString *imgURLpath = @"http://farm5.static.flickr.com/4098/4911106000_9c3a16bb59.jpg";
UIImage *imgURL = [[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: imgURLpath]]] retain];
if (imgURL != nil) { // Image was loaded successfully.
// ===== PART 2 =====
[imgHolder setImage:imgURL];
// ===== PART 2 =====
[imgHolder setUserInteractionEnabled:NO];
[imgURL release]; // Release the image now that we have a UIImageView that contains it.
}
Snippet 2: Getting an image from the resource folder
- The image I’ll be using is:
- The image above will need to be added to your applications resource folder. Note: Don’t forget to check off “Copy items to destination group’s folder. Unless that’s not your style”
// ----------------------- .h ------------------------
...
UIImageView *imgHolder;
...
@property(nonatomic, retain) IBOutlet UIImageView *imgHolder;
// ----------------------- .m ------------------------
// PART 1 - create an image object
// PART 2 - update the variable reference to the UIImageView object
// -----------------------------------------------
// ===== PART 1 =====
// note: the image in use should be in your resource folder
NSString *imgName = @"4911106000_9c3a16bb59.jpg";
UIImage *myImg = [UIImage imageNamed:imgName];
if (myImg != nil) { // Image was loaded successfully.
// ===== PART 2 =====
[imgHolder setImage:myImg];
// ===== PART 2 =====
[imgHolder setUserInteractionEnabled:NO];
[myImg release]; // Release the image now that we have a UIImageView that contains it.
}

Write a Comment