Creating UIImage
suggest changeWith local image
Swift
let image = UIImage(named: "imageFromBundleOrAsset")
Objective-C
UIImage *image = [UIImage imageNamed:@"imageFromBundleOrAsset"];
Note
The method imageNamed caches the image. Loading many large images that way can cause memory warnings and can lead the system to terminate the app. imageWithContentsOfFile does not use that cache.
With NSData
Swift
let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)
let image = UIImage(data: imageData!)
imageString must already be a Base64 string. Data(base64Encoded:) returns nil for invalid input, and imageData! crashes in that case.
With UIColor
Swift
let color = UIColor.red
let size = CGSize(width: 200, height: 200)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(origin: .zero, size: size))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Objective-C
UIColor *color=[UIColor redColor];
CGRect frame = CGRectMake(0, 0, 80, 100);
UIGraphicsBeginImageContext(frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, frame);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
With file content
Objective-C
cellCountry is a dictionary, and Country_Flag is the resource name, including its extension. The path is nil when that file is not in the main bundle.
NSString *flagName = [cellCountry objectForKey:@"Country_Flag"];
NSString *flagPath = [[NSBundle mainBundle] pathForResource:flagName ofType:nil];
UIImage *image = [UIImage imageWithContentsOfFile:flagPath];
Numbered images (photo1.jpg, photo2.jpg, and so on when myPhoto is photo):
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
for (int imageNumber = 1; self.myPhoto != nil; imageNumber++) {
NSString *fileName = [NSString stringWithFormat:@"%@%d.jpg", self.myPhoto, imageNumber];
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
UIImage *image = [UIImage imageWithContentsOfFile:path];
if (image) {
[imageArray addObject:image];
} else {
break;
}
}
// Use the array for an image-view animation.
self.myImageView.animationImages = imageArray;
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents