Skip to content

Instantly share code, notes, and snippets.

Created September 28, 2012 18:59
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Create a UIImage from an icon file and string for use in a UISegmentControl - Allows for UISegment buttons with icons and text.
#import <UIKit/UIKit.h>
@interface UIImage (UISegmentIconAndText)
+ (id) imageFromImage:(UIImage*)image string:(NSString*)string color:(UIColor*)color;
#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();
return newImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment