public

Create a UIImage from an icon file and string for use in a UISegmentControl - Allows for UISegment buttons with icons and text.

  • Download Gist
UIImage+UISegmentIconAndText.h
Objective-C
1 2 3 4 5 6 7
#import <UIKit/UIKit.h>
 
@interface UIImage (UISegmentIconAndText)
 
+ (id) imageFromImage:(UIImage*)image string:(NSString*)string color:(UIColor*)color;
 
@end
UIImage+UISegmentIconAndText.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#import "UIImage+UISegmentIconAndText.h"
 
@implementation UIImage (UISegmentIconAndText)
 
+ (id) imageFromImage:(UIImage*)image string:(NSString*)string color:(UIColor*)color
{
UIFont *font = [UIFont systemFontOfSize:12.0];
CGSize expectedTextSize = [string sizeWithFont:font];
int width = expectedTextSize.width + image.size.width + 5;
int height = MAX(expectedTextSize.height, image.size.width);
CGSize size = CGSizeMake((float)width, (float)height);
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
int fontTopPosition = (height - expectedTextSize.height) / 2;
CGPoint textPoint = CGPointMake(image.size.width + 5, fontTopPosition);
 
[string drawAtPoint:textPoint withFont:font];
// Images upside down so flip them
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, size.height);
CGContextConcatCTM(context, flipVertical);
CGContextDrawImage(context, (CGRect){ {0, (height - image.size.height) / 2}, {image.size.width, image.size.height} }, [image CGImage]);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
 
@end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.