在我們平時的開發中,有時需要給View設置一張圖片做爲背景。我們知道UIView是沒有直接提供這樣的API給我們的,我們可以另闢新徑,達到這樣的目的。
一、先簡單說下用本地的圖片創建UIImage的方式:
+ (nullable UIImage *)imageNamed:(NSString *)name;
+ (nullable UIImage *)imageWithContentsOfFile:(NSString *)path
這兩種方式都可以創建一個UIImage實例,當然它們的區別還是有的。
- 前者在創建UIImage對象時,系統會自動做了緩存,不會釋放內存,適用於小型的圖片。
- 後者在創建UIImage對象時,系統不會做圖片緩存,內存會立即釋放,適用於大型的圖片,如需要全屏的圖片。
UIImage *image1 = [UIImage imageNamed:@"image"];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
UIImage *image2 = [UIImage imageWithContentsOfFile:imagePath];
二、爲UIView設置背景圖片
1.在UIView上添加一個UIImageView
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) resizingMode:UIImageResizingModeStretch];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
imageView.image = image;
[self.view addSubview:imageView];
2.將圖片作爲UIView的背景色
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
3.其他方式(推薦)
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
self.view.layer.contents = (__bridge id _Nullable)(image.CGImage);