Forked from jonathan-beebe/UIImage+UISegmentIconAndText.h
Last active
August 29, 2015 14:04
-
-
Save psy2k/742f7e976953e39791e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <UIKit/UIKit.h> | |
@interface UIImage (UISegmentIconAndText) | |
+ (id) imageFromImage:(UIImage*)image string:(NSString*)string color:(UIColor*)color; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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