我正在使用带有contentMode的UIImageView:UIViewContentModeScaleAspectFill,其中包含的图像不能完全填充UIImageView。
例如,UIImageView的大小为:width = 480; height = 180但是里面的图像只有大小:width = 320; height = 180。因此,在80的左侧和右侧有明显的边缘。
我创建了这个函数,用第一个1x180px rect的模式填充这些80px:
- (UIImage *)repeatEdgesForImage:(UIImage *)image withDesiredSize:(CGSize)size {
UIImage *result = nil;
double ratio = image.size.height / size.height;
int width = size.width * ratio;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, image.size.height), NO, 0.0);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, 0, 1, image.size.height));
UIImage *fillImg = [UIImage imageWithCGImage:imageRef];
[fillImg drawAsPatternInRect:CGRectMake(0, 0, width, image.size.height)];
int offset = (width - image.size.width) / 2;
[image drawAtPoint:CGPointMake(offset, 0) blendMode:kCGBlendModeNormal alpha:1.0];
result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result; }
它工作正常,但结果并不完美,因为颜色略有不同:
正如您所看到的,左侧和右侧的颜色略有不同。我不确定这是来自UIImage转换为CGImage还是来自其他地方?
答案 0 :(得分:0)
我自己找到了答案。
问题出在源图像中。似乎第一个1px与其他1px略有不同......
更改此行有效:
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(5, 0, 1, image.size.height));
基本上留下5px安全区域;)然后取1px ...