UISegmentedControl image scaling

e.James picture e.James · Feb 4, 2011 · Viewed 11.3k times · Source

How can I scale down the images used in a UISegmentedControl? I am creating the segmented control programmatically:

UISegmentedControl * segmentButton;
segmentButton = [UISegmentedControl segmentedControlWithItems:
                 [NSArray arrayWithObjects:
                  [UIImage imageNamed:@"option_one.png"],
                  [UIImage imageNamed:@"option_two.png"],
                  nil]];
segmentButton.contentMode = UIViewContentModeScaleToFill;
segmentButton.frame = CGRectMake(10, 10, 200, 32);
[view addSubview:segmentButton];

The result is not what I expect. The original .png images are about 100 pixels high, and they are not scaled down to fit the 32-pixel height of the segmented control. This results in a segmented control being drawn with enormous images overlapping it:

screen shot

How can I tell the control to scale down those images?

Answer

Ludovic Landry picture Ludovic Landry · Feb 4, 2011

You should never use a "big" image to display only a small picto. The full image will be loaded in memory, and only 10% of its pixels will be displayed, so you will use a lot of memory for nothing.

What you can do if you really want to use this resource is create a thumbnail with code before, and use this new generated thumbnail.

The following method returns a new image you can use in your UISegmentedControl, and you can release the big one.

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

With your code:

UISegmentedControl * segmentButton;
segmentButton = [UISegmentedControl segmentedControlWithItems: [NSArray arrayWithObjects:
                  [self imageWithImage:[UIImage imageNamed:@"option_one.png"] scaledToSize:CGSizeMake(32, 32)],
                  [self imageWithImage:[UIImage imageNamed:@"option_two.png"] scaledToSize:CGSizeMake(32, 32)],
                  nil]];
segmentButton.contentMode = UIViewContentModeScaleToFill;
segmentButton.frame = CGRectMake(10, 10, 200, 32);
[view addSubview:segmentButton];