Customize uiswitch image properly?

Tom picture Tom · May 8, 2013 · Viewed 17.6k times · Source

I have an UISwitch in my iOS 6 app, that's on and off image is customised.

self.testSwitch.onImage = [UIImage imageNamed:@"on"]; 
self.testSwitch.offImage = [UIImage imageNamed:@"off"];

I use 77 points wide and 22 points tall image for this purpose (154x44 in retina), as it is stated in the documentation. But my image does not fit to my uiswitch, it seems ugly, the default style hides my one, like on the attached image.

enter image description here

What should I set to make it work in a proper way?

Answer

matt picture matt · May 8, 2013

Here is code from my book. This is not exactly what you want to do, but it shows the technique and will get you started! Notice that I'm using 79 by 27 (not sure where you got your numbers from):

UIGraphicsBeginImageContextWithOptions(CGSizeMake(79,27), NO, 0);
[[UIColor blackColor] setFill];
UIBezierPath* p = [UIBezierPath bezierPathWithRect:CGRectMake(0,0,79,27)];
[p fill];
NSMutableParagraphStyle* para = [NSMutableParagraphStyle new];
para.alignment = NSTextAlignmentCenter;
NSAttributedString* att =
    [[NSAttributedString alloc] initWithString:@"YES" attributes:
        @{
            NSFontAttributeName:[UIFont fontWithName:@"GillSans-Bold" size:16],
            NSForegroundColorAttributeName:[UIColor whiteColor],
            NSParagraphStyleAttributeName:para
        }];
[att drawInRect:CGRectMake(0,5,79,22)];
UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.sw2.onImage = im;

Looks like this:

enter image description here