iOS Swift load an Image from App Resource Bundle using imageNamed and imageWithContentsOfFile methods

imageNamed method

This method looks in the system caches for an image object with the specified name and returns the variant of that image that is best suited for the main screen. If a matching image object is not already in the cache, this method locates and loads the image data from disk or from an available asset catalog, and then returns the resulting object.

imageWithContentsOfFile method

This method does not cache the image object. If you have an image file that will only be displayed once and wish to ensure that it does not get added to the system's cache, you should instead create your image using imageWithContentsOfFile. This will keep your single-use image out of the system image cache, potentially improving the memory use characteristics of your app.

iOS Swift load an Image from App Resource Bundle

import UIKit

class ViewController1: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "Main View"
        
        let imageView = UIImageView()
        imageView.frame = CGRect(x: 50, y: 50, width: 200, height: 200)
        imageView.contentMode = .scaleAspectFit
        view.addSubview(imageView)
        
        //Image caching
        let myImageName = "apple.png"
        let myImage = UIImage(named: myImageName)
        imageView.image = myImage
        
        let imageView2 = UIImageView()
        imageView2.frame = CGRect(x: 300, y: 50, width: 200, height: 200)
        imageView2.contentMode = .scaleAspectFit
        view.addSubview(imageView2)
        
        //No image caching
        imageView2.image = getImage(named: "apple_black")!
        
    }
    
    func getImage (named name : String) -> UIImage?
    {
        if let imgPath = Bundle.main.path(forResource: name, ofType: ".png")
        {
            return UIImage(contentsOfFile: imgPath)
        }
        return nil
    }
    
    
}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.