UIImageView的集中初始化方法

1.使用imageWithContentsOfFile:初始化

UIImage*image = [UIImageimageWithContentsOfFile:[[NSBundlemainBundle]pathForResource:@"1.png"ofType:nil]];

UIImageView*imageView = [[UIImageViewalloc]init];

imageView.frame=CGRectMake(50,50,275,275);

imageView.image= image;

imageView.backgroundColor= [UIColoryellowColor];

[self.viewaddSubview:imageView];

2,使用initWithContentsOfFile:初始化

UIImage*image1 = [[UIImagealloc]initWithContentsOfFile:[NSStringstringWithFormat:@"%@/1.png",[[NSBundlemainBundle]resourcePath]]] ;

UIImageView*imageView1 = [[UIImageViewalloc]init];

imageView1.frame=CGRectMake(50,350,275,275);

imageView1.image= image1;

imageView1.backgroundColor= [UIColoryellowColor];

[self.viewaddSubview:imageView1];

3,使用imageNamed:初始化

UIImage*image2 = [UIImageimageNamed:@"1.png"];

UIImageView*imageView2 = [[UIImageViewalloc]init];

imageView2.frame=CGRectMake(50,350,275,275);

imageView2.image= image2;

imageView2.backgroundColor= [UIColoryellowColor];

[self.viewaddSubview:imageView2];


我主要想講一下imageNamed:和前兩種分別的使用情況:

當一些圖片占十幾KB而已并且常用的時候,建議使用imageNamed:

imageNamed:這個方法會將圖片緩存到內存中 ,使用圖片時會去尋找緩存,如果找不到才去NSBundle中找,找到后緩存,返回對象。找不到返回nil

但是有個弊端:程序結束的時候,這個圖片才被釋放掉,所以占用的內存很多。

前兩種是真接找路徑中的圖片,找不到返回nil.若使用的圖片是高清大圖不常用的時候,建議使用imageWithContentsOfFile:或者initWithContentsOfFile:

需要的時候 再加載。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容