我正在使用带有 contentMode:UIViewContentModeScaleAspectFill 的 UIImageView,其中包含未完全填充 UIImageView 的图像。
例如 UIImageView 的大小为:width=480;height=180,但内部图像的大小仅为:width=320;height=180。因此80左右两侧有明显的边距。
我创建了这个函数来用第一个 1x180px 矩形的图案填充这些 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 的转换或来自其他地方?
最佳答案
我自己找到了答案。
问题出在源图像中。看起来第一个 1px 与其余的略有不同......
更改此行有效:
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(5, 0, 1, image.size.height));
基本上留下 5px 安全区域;),然后占用 1px ...
关于ios - 使用 UIGraphics 和 CGImage 从 UIImage 创建新图像时,颜色略有不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16268987/