Skip to content

Instantly share code, notes, and snippets.

@jonathan-beebe
Created September 28, 2012 18:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jonathan-beebe/3801542 to your computer and use it in GitHub Desktop.
Save jonathan-beebe/3801542 to your computer and use it in GitHub Desktop.
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;
@end
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment