在iOS的開(kāi)發(fā)中崔拥,有時(shí)候美工只發(fā)來(lái)一張方形的默認(rèn)圖片
placeholderImage.png
但是在項(xiàng)目里面,圖片的比例各有不同袒啼,而通過(guò)設(shè)置contentMode屬性的方法是行不通的:
UIViewContentModeScaleToFill:
test1.png
UIViewContentModeScaleAspectFit:
test2.png
UIViewContentModeScaleAspectFill:
test3.png
當(dāng)然砂轻,你也可以要求美工切一張背景透明拱礁,然后自己設(shè)置view的背景色,或者用取色器確定顏色然后設(shè)置背景色绎秒。
但是浦妄,在這里我采用另外一種方法,就是通過(guò)程序取圖片邊界背景色见芹,然后自動(dòng)設(shè)置view的背景色剂娄,這樣,即使在placeholderImage更換的時(shí)候辆童,也不用修改代碼
- (void)viewDidLoad {
[super viewDidLoad];
for (int i = 1; i <= 5; i++) {
UIImageView *vi = [self valueForKey:[NSString stringWithFormat:@"test%d", i]];
[self setupDefineImageAutoAdaptation:[UIImage imageNamed:@"img_default_5"] withView:vi];
}
}
- (void)setupDefineImageAutoAdaptation:(UIImage *)image withView:(UIImageView *)vi {
vi.contentMode = UIViewContentModeScaleAspectFit;
vi.image = image;
NSArray<NSNumber *> *theColorValueArray = [self getSamplePixelToImageBackGroundColor:image];
vi.backgroundColor = [UIColor colorWithRed:[theColorValueArray[0] intValue]/255.0f green:[theColorValueArray[1] intValue]/255.0f blue:[theColorValueArray[2] intValue]/255.0f alpha:1];
}
// 獲取色位宜咒,
- (NSArray<NSNumber *> *)getSamplePixelToImageBackGroundColor:(UIImage *)image {
CGImageRef cgimage = image.CGImage;
size_t bpr = CGImageGetBytesPerRow(cgimage);//獲取位圖每一行的字節(jié)數(shù)
size_t bpp = CGImageGetBitsPerPixel(cgimage);//獲取組成每一像素的位數(shù)
size_t bpc = CGImageGetBitsPerComponent(cgimage);//獲取每個(gè)色位的位數(shù)
size_t bytes_per_pixel = bpp / bpc;//獲取組成每一像素的色位數(shù),這里是4(如(255,255,255,255))
// CGBitmapInfo info = CGImageGetBitmapInfo(cgimage);
CGDataProviderRef provider = CGImageGetDataProvider(cgimage);
NSData* data1 = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data1 bytes];
const uint8_t* pixel = &bytes[1 * bpr + 1 * bytes_per_pixel];//獲取位圖的第一行第一列像素點(diǎn)作為參考
return @[@(pixel[0]), @(pixel[1]), @(pixel[2])];//rgb返回前3位
}
結(jié)果:
test5.png
我們可能會(huì)將上述功能添加到UIImageView的擴(kuò)展把鉴,所以代碼類(lèi)似于一下:
UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kWidth/kCellScale)];
[img setupDefineImageAutoAdaptation:@"默認(rèn)圖片"];
[img sd_setImageWithURL:ImageUrl(dataModel.resUrl) placeholderImage:@"默認(rèn)圖片"];