在iOS的开发中,有时候美工只发来一张方形的默认图片

但是在项目里面,图片的比例各有不同,而通过设置contentMode属性的方法是行不通的:
UIViewContentModeScaleToFill:

UIViewContentModeScaleAspectFit:

UIViewContentModeScaleAspectFill:

当然,你也可以要求美工切一张背景透明,然后自己设置view的背景色,或者用取色器确定颜色然后设置背景色。
但是,在这里我采用另外一种方法,就是通过程序取图片边界背景色,然后自动设置view的背景色,这样,即使在placeholderImage更换的时候,也不用修改代码
- (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);//获取位图每一行的字节数
size_t bpp = CGImageGetBitsPerPixel(cgimage);//获取组成每一像素的位数
size_t bpc = CGImageGetBitsPerComponent(cgimage);//获取每个色位的位数
size_t bytes_per_pixel = bpp / bpc;//获取组成每一像素的色位数,这里是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];//获取位图的第一行第一列像素点作为参考
return @[@(pixel[0]), @(pixel[1]), @(pixel[2])];//rgb返回前3位
}
结果:

我们可能会将上述功能添加到UIImageView的扩展,所以代码类似于一下:
UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kWidth/kCellScale)];
[img setupDefineImageAutoAdaptation:@"默认图片"];
[img sd_setImageWithURL:ImageUrl(dataModel.resUrl) placeholderImage:@"默认图片"];
网友评论