Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psy2k/742f7e976953e39791e2 to your computer and use it in GitHub Desktop.
Save psy2k/742f7e976953e39791e2 to your computer and use it in GitHub Desktop.
#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 sizeWithAttributes:@{NSFontAttributeName:font}];
int width = expectedTextSize.width + image.size.width + 5;
int height = MAX(expectedTextSize.height, image.size.height);
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 withAttributes:@{NSFontAttributeName: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