创建 UIImage
有了本地形象
迅速
let image = UIImage(named: "imageFromBundleOrAsset")
Objective-C
UIImage *image = [UIImage imageNamed:@"imageFromBundleOrAsset"];
注意
imageNamed
方法将图像的内容缓存到内存中。以这种方式加载许多大图像可能会导致低内存警告,从而导致应用程序被终止。这可以通过利用UIImage
的方法imageWithContentsOfFile
来修复,该方法不使用缓存。
使用 NSData
迅速
let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)
let image = UIImage(data: imageData!)
使用 UIColor
迅速
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();
随着文件内容
Objective-C
例:
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[cellCountry objectForKey:@"Country_Flag"] ofType:nil]];
使用数组:
例:
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
for (int imageNumber = 1; self.myPhoto != nil; imageNumber++) {
NSString *fileName = [NSString stringWithFormat:@"%@.jpg", self.myPhoto];
// check if a file exists
if ([UIImage imageNamed:fileName]) {
// if it exists, add it to the array
[imageArray addObject:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"%@", fileName] ofType:@""]]];
} else {
break;
}
}
//在此处使用动画的图像数组:
self.myImageView.animationImages = imageArray;