Domanda

I am using a UIImageView with contentMode:UIViewContentModeScaleAspectFill which contains an image that does not fill the UIImageView entirely.

For example the UIImageView has the size: width=480;height=180 but the image inside only has the size: width=320;height=180. Hence there is a clear margin at the left and right side of 80.

I created this function to fill these 80px with a pattern of the first 1x180px rect:

- (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; }

It is working fine, but the result is not quite perfect, because the colors are slightly different:

enter image description here

As you can see the left and right side are slightly different in color. I am not sure if this comes from the conversion of UIImage to CGImage or from somewhere else?

È stato utile?

Soluzione

I found the answer myself.

The problem was in the source image. It seems that the first 1px is slightly different than the rest...

changing this line works:

CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(5, 0, 1, image.size.height));

Basically leaving a 5px security zone ;) and then taking 1px ...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top