Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clip larger images to fit into tabBar icons in tabBarController built programmatically.

I have created a tab controller programmatically.

Now, I wanted to add images to the different tabs, for which I used :

  self.tabBarItem.image = [UIImage imageNamed:@"Sample_Image.png"];

The problem is Sample_image is larger in size than is required by tab.

So just want to know how can I clip the image to fit into tabs.

like image 240
Satish Gupta Avatar asked Apr 01 '14 08:04

Satish Gupta


2 Answers

Sample_image is larger in size than is required by tab.

Try this piece of code as this will resize the required image and return an UIImage instance with 30x30 size (size required for UITabbar).

UIImage *image = [UIImage imageNamed:@"Sample_Image.png"];
self.tabBarItem.image = [self imageWithImage:image scaledToSize:CGSizeMake(30, 30)];

Add This method

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
like image 90
Buntylm Avatar answered Oct 24 '22 21:10

Buntylm


Rename your image to [email protected]. This is called pixel doubling for the Retina Display.

Without the @2x iOS doesn't know that it should apply a scale factor and it will be used as it is and though it should be halved.

 [[[self tabBarController] tabBar] setBackgroundImage:[UIImage imageNamed:@"[email protected]"]];

In reality there should be:

Sample_Image png (45 px or so)

[email protected] so you say only:

[[[self tabBarController] tabBar] setBackgroundImage:[UIImage imageNamed:@"Sample_Image.png"]];
like image 44
Irfan Avatar answered Oct 24 '22 22:10

Irfan