-1

So I have an image that is a circle which I want to scale down to a new size.

enter image description here

When I scale down, the resultant is a square with the circle with diameter = side of the square, and there is a white background color. How do I get an image that is exactly the same shape?

+ (UIImage *)imageWithImage:(UIImage *)image customScaledToSize:(CGSize)newSize
{
//UIGraphicsBeginImageContext(newSize);
UIGraphicsBeginImageContextWithOptions(newSize, NO, [UIScreen mainScreen].scale);

[[UIColor clearColor] set];
UIRectFill(CGRectMake(0, 0, newSize.width, newSize.height));

[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Legolas
  • 12,145
  • 12
  • 79
  • 132
  • Maybe try this? http://stackoverflow.com/a/537697/2518285 – Brett Donald May 04 '16 at 23:01
  • That does not help. It would still be a square. – Legolas May 05 '16 at 08:46
  • Your actual problem is the white color instead of clear background? – phi May 05 '16 at 09:03
  • @phi Yes, circle image scaled down to smaller size has white background – Legolas May 05 '16 at 20:59
  • So you're saying that your original image is a circle on a transparent background, but that when you scale it, you get a white background? Your code is similar to this very popular answer http://stackoverflow.com/a/2658801/2518285 but yours has a UIRectFill, whereas the answer does not. Suggest trying without UIRectFill. And are you 100% sure your original image has a transparent background? – Brett Donald May 06 '16 at 00:14
  • Yes, I am positive. Ive added the image to the question – Legolas May 06 '16 at 08:49
  • I've tried the code in your question, with the image attached above, and the transparent parts of the image are maintained, with or without the `UIRectFill`. Can you add screenshots of the effect you're seeing? I suspect there's something else going on that is not included in the question. – jrturton May 06 '16 at 09:02
  • Ok found the issue for it. I was saving the image to disk as JPEG with compression. FML. Did not see that. Saving as png is the right way to go.. Haha sorry for wasting all of your time – Legolas May 06 '16 at 22:59
  • @jrturton really appreciate you trying out the code for me. – Legolas May 06 '16 at 23:01
  • 1
    You should add that as an answer - JPEG doesn't support transparency. – jrturton May 07 '16 at 06:14
  • Suggest you delete this question, seeing as it mentions scaling but the answer has nothing to do with scaling. – Brett Donald May 12 '16 at 01:41

1 Answers1

0

The reason for the problem was that the image was saved as a JPEG right before scaling, and JPEG does not support transparency.

Saving as PNG was the right way to go.

Legolas
  • 12,145
  • 12
  • 79
  • 132