+ (UIImage *)getImage:(NSString *)name
{
UIColor *color = [self randomColor]; //获取随机颜色
CGRect rect = CGRectMake(0.0f, 0.0f, 128, 128);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSString *headerName = nil;
if (name.length < 3) {
headerName = name;
}else{
headerName = [name substringFromIndex:name.length-2];
}
UIImage *headerimg = [self imageToAddText:img withText:headerName];
return headerimg;
}
//随机颜色
+ (UIColor *)randomColor
{
CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;
return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}
//把文字绘制到图片上
+ (UIImage *)imageToAddText:(UIImage *)img withText:(NSString *)text
{
//1.获取上下文
UIGraphicsBeginImageContext(img.size);
//2.绘制图片
[img drawInRect:CGRectMake(0, 0, img.size.width, img.size.height)];
//3.绘制文字
CGRect rect = CGRectMake(0,(img.size.height-45)/2, img.size.width, 25);
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
//文字的属性
NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:20],NSParagraphStyleAttributeName:style,NSForegroundColorAttributeName:[UIColor whiteColor]};
//将文字绘制上去
[text drawInRect:rect withAttributes:dic];
//4.获取绘制到得图片
UIImage *watermarkImg = UIGraphicsGetImageFromCurrentImageContext();
//5.结束图片的绘制
UIGraphicsEndImageContext();
return watermarkImg;
}
iOS 生成一张颜色随机并带文字的图片
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 万恶的需求给了一张默认图,但是要求给所有的ImageView默认都给这张默认图,但是ImageView有很多,si...