0

I have two UIImageViews and I want to copy the image from one to the other and adjust the color but it's causing weird stretching.

Here is the code that I use to make the copy:

_selectedIcon.image = groupView.icon;
[ViewUtils colorImageView:_selectedIcon withRed:0.843 Green:0.3176 andBlue:0.066667];

If I only use the first line it copies the image fine and looks like this:

Correct

It's a bit larger because it's meant to look highlighted. But it copies over and scales correctly. Then when I try to color it, it does this:

Wrong

Here is the code that I use to color the image:

+(void)colorImageView:(UIImageView*)source withRed:(CGFloat)red Green:(float)green andBlue:(float)blue
{
    // Create a context containing the image.
    UIGraphicsBeginImageContext(source.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // The mask needs to be upside down for some reason
    CGContextTranslateCTM(context, 0, source.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextClipToMask(context, source.bounds, [source.image CGImage]);
    CGContextFillRect(context, source.bounds);

    [[UIColor colorWithRed:red green:green blue:blue alpha:1.0] set];
    UIBezierPath *imagePath = [UIBezierPath bezierPathWithRect:source.bounds];
    [imagePath fill];
    // Retrieve the new image.
    source.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

I have tries many different ways of scaling the image in the coloring code and nothing seems to work. Does anyone have a suggestion?

CaseyB
  • 24,780
  • 14
  • 77
  • 112

1 Answers1

0

I figured it out. The image was stretching to fit the whole UIImageView so I needed to adjust the bounds so that it scaled correctly. Here's the code I used:

float ratioX = source.bounds.size.width / source.image.size.width;
float ratioY = source.bounds.size.height / source.image.size.height;
float ratio = MIN(ratioX, ratioY);
CGRect bounds = CGRectMake(0, 0, source.image.size.width * ratio, source.image.size.height * ratio);
CaseyB
  • 24,780
  • 14
  • 77
  • 112