iOS 根据昵称姓名string绘制对应头像图片

最近因为项目需求,需要根据不同的nikeName给不同的群设置含有群名的群头像。
效果如下:

iOS 根据昵称姓名string绘制对应头像图片_第1张图片
WX20170518-175324.png

大概思路就是,定义几种颜色作为随机使用的底色,根据string对应的hash值除以颜色的数量取余的绝对值来确定每个string对应的颜色,然后绘制一个对应颜色的纯色图片,再在图片中心绘制需要显示的文字。这样就可以得到想要的效果了。
显示文本的筛选方法是:含有字母就取前两个字符,不含字母的话,长度为1就取一个字符,长度为2就取两个字符,长度为3和4取后两个字符,长度超过4默认取前两个字符显示。

写了个分类,方便调用

UIImage+JWNameImage.h

//
//  UIImage+JWNameImage.h
//  HMClient
//
//  Created by jasonwang on 2017/5/18.
//  Copyright © 2017年 YinQ. All rights reserved.
//  根据string返回对应头像图片分类

#import 

@interface UIImage (JWNameImage)
+ (UIImage *)JW_acquireNameImageWithNameString:(NSString *)string imageSize:(CGSize)size;
@end

UIImage+JWNameImage.m

//
//  UIImage+JWNameImage.m
//  HMClient
//
//  Created by jasonwang on 2017/5/18.
//  Copyright © 2017年 YinQ. All rights reserved.
//

#import "UIImage+JWNameImage.h"

@implementation UIImage (JWNameImage)

+ (UIImage *)JW_acquireNameImageWithNameString:(NSString *)string imageSize:(CGSize)size {
    return [UIImage JW_createNikeNameImageName:[UIImage JW_dealWithNikeName:string] imageSize:size];
}

// 按规则截取nikeName
+ (NSString *)JW_dealWithNikeName:(NSString *)nikeName {
    // 筛除部分特殊符号
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"【】"];
    nikeName = [nikeName stringByTrimmingCharactersInSet:set];
    NSString *showName = @"";
    NSString *tempName = @"";
    
    NSRange range1 = [nikeName rangeOfString:@"-"];
    
    if (range1.length) {
        // 含有“-”
        tempName = [nikeName substringToIndex:range1.location];
    }
    else {
        // 不含“-”
        tempName = nikeName;
    }
    
    NSRange range2 = [tempName rangeOfString:@"("];
    
    if (range2.length) {
        // 含有“(”
        tempName = [tempName substringToIndex:range2.location];
    }
    else {
        // 不含“(”
        tempName = tempName;
    }
    
    if ([UIImage JW_isStringContainLetterWith:tempName]) {
        // 含有字母取前两个
        showName = [tempName substringToIndex:2];
    }
    else {
        // 不含字母
        if (!tempName.length) {
            
        }
        else if (tempName.length == 1)
        {
            showName = [tempName substringToIndex:1];
        }
        else if (tempName.length == 2)
        {
            showName = [tempName substringToIndex:2];
        }
        else if (tempName.length == 3)
        {
            showName = [tempName substringFromIndex:1];
        }
        else if (tempName.length == 4)
        {
            showName = [tempName substringFromIndex:2];
        }
        else {
            showName = [tempName substringToIndex:2];
        }
    }
    return showName;
}
// 检查是否含有字母
+ (BOOL)JW_isStringContainLetterWith:(NSString *)str {
    if (!str) {
        return NO;
    }
    NSRegularExpression *numberRegular = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSInteger count = [numberRegular numberOfMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
    //count是str中包含[A-Za-z]数字的个数,只要count>0,说明str中包含数字
    if (count > 0) {
        return YES;
    }
    return NO;
}
// 根据nikeName绘制图片
+ (UIImage *)JW_createNikeNameImageName:(NSString *)name imageSize:(CGSize)size{
    NSArray *colorArr = @[@"17c295",@"b38979",@"f2725e",@"f7b55e",@"4da9eb",@"5f70a7",@"568aad"];
    UIImage *image = [UIImage JW_imageColor:[UIImage JW_colorWithHexString:colorArr[ABS(name.hash % colorArr.count)] alpha:1.0] size:size cornerRadius:size.width / 2];
    
    UIGraphicsBeginImageContextWithOptions (size, NO , 0.0 );
    
    [image drawAtPoint : CGPointMake ( 0 , 0 )];
    
    // 获得一个位图图形上下文
    
    CGContextRef context= UIGraphicsGetCurrentContext ();
    
    CGContextDrawPath (context, kCGPathStroke );
    
    // 画名字
    
    CGSize nameSize = [name sizeWithAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]}];
    
    [name drawAtPoint : CGPointMake ( (size.width  - nameSize.width) / 2 , (size.height  - nameSize.height) / 2 ) withAttributes : @{ NSFontAttributeName :[ UIFont systemFontOfSize:14], NSForegroundColorAttributeName :[ UIColor colorWithHexString:@"ffffff" ] } ];
    
    // 返回绘制的新图形
    
    UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext ();
    
    UIGraphicsEndImageContext ();
    
    return newImage;
    
}

+ (UIImage *)JW_imageColor:(UIColor *)color size:(CGSize)size cornerRadius:(CGFloat)radius {
    if (CGSizeEqualToSize(size, CGSizeZero)) {
        size = CGSizeMake(1, 1);
    }
    
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, 0, [UIScreen mainScreen].scale);
    [color set];
    UIRectFill(rect);
    UIImage *colorImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIGraphicsBeginImageContextWithOptions(size, 0, [UIScreen mainScreen].scale);
    
    [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius] addClip];
    [colorImage drawInRect:rect];
    
    colorImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return colorImage;
}

+ (id)JW_colorWithHexString:(NSString*)hexColor alpha:(CGFloat)alpha {
    
    unsigned int red,green,blue;
    NSRange range;
    
    range.length = 2;
    range.location = 0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&red];
    
    range.location = 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&green];
    
    range.location = 4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&blue];
    
    UIColor* retColor = [UIColor colorWithRed:(float)(red/255.0f)green:(float)(green / 255.0f) blue:(float)(blue / 255.0f)alpha:alpha];
    return retColor;
}
@end

你可能感兴趣的:(iOS 根据昵称姓名string绘制对应头像图片)