建立 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;