? ? ?UIImage *image = [UIImageimageNamed:@"image.jpg"];//這種不釋放內(nèi)存,要緩存
? ? ?NSString *path = [[NSBundlemainBundle]pathForResource:@"image"ofType:@"jpg"];
? ? ?UIImage *image1 = [UIImageimageWithContentsOfFile:path];//這種會釋放內(nèi)存
? ? ?那么,為UIView添加背景圖片可以有三種方法:
? ? ?1.在UIView上添加一個UIImageView
? ? ?UIImageView *imageView = [[UIImageViewalloc]initWithFrame:self.view.bounds];
? ? ?imageView.image = [[UIImageimageNamed:@"image.jpg"]stretchableImageWithLeftCapWidth:10topCapHeight:10];
? ? ?[self.viewaddSubview:imageView];
? ? ?//這種方式,如果原始圖片不小不夠,則會拉伸以滿足View的尺寸,在View釋放之后沒有內(nèi)存保留。
? ? ?2.將圖片作為UIView的背景色
? ? ?//1.imageNamed方式
? ? ?self.view.backgroundColor = [UIColorcolorWithPatternImage:[UIImageimageNamed:@"image.jpg"]];
? ? ?//2.方式
? ? ?NSString *path = [[NSBundlemainBundle]pathForResource:@"image"ofType:@"jpg"];
? ? ?self.view.backgroundColor = [UIColorcolorWithPatternImage:[UIImageimageWithContentsOfFile:path]];
? ? ?//這兩種方式都會在生成color時占用大量的內(nèi)存。如果圖片大小不夠,就會平鋪多張圖片,不會去拉伸圖片以適應(yīng)View的大小。
? ? ?//在View釋放后,1中的color不會跟著釋放,而是一直存在內(nèi)存中;2中的color會跟著釋放掉,當然再次生成color時就會再次申請內(nèi)存。
3.其他方式(推薦)
? ? ?NSString *path = [[NSBundlemainBundle]pathForResource:@"image"ofType:@"jpg"];
? ? ?UIImage *image = [UIImageimageWithContentsOfFile:path];
? ? ?self.view.layer.contents = (id)image.CGImage;