代码如下:
#import@interface UIImage (mask)
/**
* 在一张背景图上绘制文字并且居中
*
* @param str 要绘制到图片上的文字
* *
*
*/
+ (UIImage *)createOtherMerchantImage:(NSString *)str size:(CGSize)size;
@end
#import "UIImage+mask.h
"@implementation UIImage (mask)
+ (UIImage *)createOtherMerchantImage:(NSString *)str size:(CGSize)size{ NSString * substring = [str substringFromIndex:str.length-2];
int texthash = (int)[str hash];
texthash=abs(texthash)+1;
int lastNum=texthash%10;
if (lastNum>=5) {
lastNum=lastNum-5;
}
NSArray* colorArr=@[
[UIColor colorWithRed:237/255.0f green:151/255.0f blue:151/255.0f alpha:1.0],
[UIColor colorWithRed:237/255.0f green:197/255.0f blue:151/255.0f alpha:1.0],
[UIColor colorWithRed:151/255.0f green:198/255.0f blue:237/255.0f alpha:1.0],
[UIColor colorWithRed:145/255.0f green:224/255.0f blue:152/255.0f alpha:1.0],
[UIColor colorWithRed:176/255.0f green:164/255.0f blue:162/255.0f alpha:1.0],
];
NSDictionary * fontAttributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:15],//设置文字的字体
NSForegroundColorAttributeName: [UIColor whiteColor]
};
CGSize textSize = [substring sizeWithAttributes:fontAttributes];
CGPoint drawPoint = CGPointMake((size.width - textSize.width)/2, (size.height - textSize.height)/2);
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
CGContextSetFillColorWithColor(context, colorArr[lastNum].CGColor);
[path fill];
[substring drawAtPoint:drawPoint withAttributes:fontAttributes];
UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImg;
}
@end