图片处理

头像图片处理,没有图片时将姓名的首字母显示到图片上

/*
NSString *name = @"name";
// 获取姓名首字母
NSString *charStr = [self transformToPinyin:name];
UIImage *img = [self getImage:charStr];
imageV.image = img;
*/

  • (NSString *)transformToPinyin:(NSString *)name {
    NSMutableString *mutableString = [NSMutableString stringWithString:name];
    CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
    mutableString = (NSMutableString *)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
    NSString *tempStr = [mutableString stringByReplacingOccurrencesOfString:@"'" withString:@""];
    NSArray *arr = [tempStr componentsSeparatedByString:@" "];
    NSString *s = @"";
    for (NSString *str in arr) {
    s = [s stringByAppendingString:[str substringToIndex:1]];
    }
    s = [s uppercaseString];
    if (s.length >= 2) {
    s = [s substringToIndex:2];
    }
    return s;
    }

  • (UIImage *)getImage:(NSString *)name
    {
    UIColor *color = [self randomColor]; //获取随机颜色
    CGRect rect = CGRectMake(0.0f, 0.0f, 24, 24);
    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,2, img.size.width, img.size.height - 8);
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    style.alignment = NSTextAlignmentCenter;
    //文字的属性
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15],NSParagraphStyleAttributeName:style,NSForegroundColorAttributeName:[UIColor whiteColor]};
    //将文字绘制上去
    [text drawInRect:rect withAttributes:dic];
    //4.获取绘制到得图片
    UIImage *watermarkImg = UIGraphicsGetImageFromCurrentImageContext();
    //5.结束图片的绘制
    UIGraphicsEndImageContext();

    return watermarkImg;
    }

你可能感兴趣的:(图片处理)