iOS UIImageView文字头像,首字母缩略头像

简介: iOS UIImageView文字头像,首字母缩略头像

前言


提供类似于通讯录头像,支持汉字转拼音,小写转大写,分割等操作

头像浏览


GitHub地址:KJEmitterView

1.png


简单介绍 Property & API

NS_ASSUME_NONNULL_BEGIN
@interface UIImageViewLettersInfo : NSObject
/// 图片颜色,默认随机色
@property(nonatomic,strong)UIColor *color;
/// 是否切圆,默认yes
@property(nonatomic,assign)BOOL circle;
/// 是否取第一个,默认yes
@property(nonatomic,assign)BOOL frist;
/// 是否将汉字转拼音,默认NO
@property(nonatomic,assign)BOOL pinyin;
/// 是否将拼音转为大写,默认yes
@property(nonatomic,assign)BOOL uppercase;
/// 以该符号分割显示第一个,默认空格
@property(nonatomic,strong)NSString *partition;
/// 是否分割,默认NO
@property(nonatomic,assign)BOOL isPartition;
/// 文字信息
@property(nonatomic,strong)NSDictionary *attributes;
@end
@interface UIImageView (KJLetters)
/// 显示文字图片
- (void)kj_imageViewWithText:(NSString*)text LettersInfo:(UIImageViewLettersInfo*(^)(UIImageViewLettersInfo *info))block;
/// 浏览头像,点击全屏展示
- (void)kj_headerImageShowScreen;
/// 浏览头像,背景颜色
- (void)kj_headerImageShowScreenWithBackground:(UIColor*)color;
@end
NS_ASSUME_NONNULL_END


kj_imageViewWithText:LettersInfo:


内部我采用回调的方式来接收外界UIImageViewLettersInfo参数


使用示例


CGFloat x,y;
CGFloat sp = kAutoW(10);
CGFloat w = (kScreenW-sp*5)/4.;
CGFloat h = w+w/2;
NSArray *name = @[@"回头",@"看看",@"Z Jian",@"I Love You",@"你好",@"喜 欢",@"痛苦的信 仰",@"吗?",@"End",@"hao ba"];
for (int k=0; k<name.count; k++) {
    x = k%4*(w+sp)+sp;
    y = k/4*(h+sp*2)+sp+64+sp*2;
    UILabel *label = [UILabel kj_createLabelWithText:name[k] FontSize:14 TextColor:UIColor.orangeColor];
    label.backgroundColor = [UIColor.orangeColor colorWithAlphaComponent:0.2];
    label.borderWidth = 1;
    label.borderColor = UIColor.orangeColor;
    label.frame = CGRectMake(x, y, w, w/3);
    [self.view addSubview:label];
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.frame = CGRectMake(x, y+w/3+10, w, w);
    [self.view addSubview:imageView];
    [imageView kj_imageViewWithText:name[k] LettersInfo:^UIImageViewLettersInfo * _Nonnull(UIImageViewLettersInfo * _Nonnull info) {
        if (k==0) {
            info.circle = NO;
            info.color = UIColor.orangeColor;
        }else if (k==1) {
            info.pinyin = YES;
            info.uppercase = NO;
        }else if (k==2) {
        }else if (k==3) {
            info.partition = @" ";
            info.isPartition = YES;
        }else if (k==4) {
            info.pinyin = YES;
        }else if (k==5) {
            info.frist = NO;
            info.isPartition = YES;
        }else if (k==6) {
            info.frist = NO;
            info.isPartition = YES;
        }else if (k==9) {
            info.frist = NO;
            info.uppercase = NO;
            info.isPartition = YES;
        }
        return info;
    }];
    [imageView kj_AddTapGestureRecognizerBlock:^(UIView * _Nonnull view, UIGestureRecognizer * _Nonnull gesture) {
        [imageView kj_headerImageShowScreen];
    }];
}


Category

//
//  UIImageView+KJLetters.m
//  KJExtensionHandler
//
//  Created by 杨科军 on 2020/11/17.
//  https://github.com/yangKJ/KJExtensionHandler
#import "UIImageView+KJLetters.h"
#import <objc/runtime.h>
@implementation UIImageView (KJLetters)
/// 显示文字图片
- (void)kj_imageViewWithText:(NSString*)text LettersInfo:(UIImageViewLettersInfo*(^)(UIImageViewLettersInfo *info))block{
    UIImageViewLettersInfo *info = [[UIImageViewLettersInfo alloc]init];
    if (block) {
        info = block(info);
        if (!info.attributes) info.attributes = @{NSFontAttributeName:[self fontForFontName:nil],NSForegroundColorAttributeName:[UIColor whiteColor]};
        if (info.pinyin) {
            text = [self pinYin:text];
            if (info.uppercase) text = text.uppercaseString;
        }
        if (info.frist) {
            NSRange range = [text rangeOfComposedCharacterSequencesForRange:NSMakeRange(0,1)];
            text = [text substringWithRange:range];
        }else{
            if (info.isPartition) {
                NSMutableString *displayString = [NSMutableString stringWithString:info.partition];
                NSMutableArray *words = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy];
                if ([words count]) {
                    NSString *firstWord = [words firstObject];
                    if ([firstWord length]) {
                        NSRange range = [firstWord rangeOfComposedCharacterSequencesForRange:NSMakeRange(0,1)];
                        [displayString appendString:[firstWord substringWithRange:range]];
                    }
                    if ([words count] >= 2) {
                        NSString *lastWord = [words lastObject];
                        while ([lastWord length] == 0 && [words count] >= 2) {
                            [words removeLastObject];
                            lastWord = [words lastObject];
                        }
                        if ([words count] > 1) {
                            NSRange lastLetterRange = [lastWord rangeOfComposedCharacterSequencesForRange:NSMakeRange(0,1)];
                            [displayString appendString:[lastWord substringWithRange:lastLetterRange]];
                        }
                    }
                }
                if (info.uppercase) {
                    text = [displayString uppercaseString];
                }else {
                    text = displayString.mutableCopy;
                }
            }
        }
        self.image = [self imageSnapshotFromText:text Color:info.color Circle:info.circle TextAttributes:info.attributes];
    }
}
- (NSString*)pinYin:(NSString*)text{
    NSMutableString *string = [text mutableCopy];
    CFStringTransform((CFMutableStringRef)string,NULL,kCFStringTransformMandarinLatin,NO);
    CFStringTransform((CFMutableStringRef)string,NULL,kCFStringTransformStripDiacritics,NO);
    return string;
}
- (UIFont*)fontForFontName:(NSString*)fontName {
    CGFloat fontSize = CGRectGetWidth(self.bounds) * 0.42;
    if (fontName) {
        return [UIFont fontWithName:fontName size:fontSize];
    }else{
        return [UIFont systemFontOfSize:fontSize];
    }
}
- (UIImage*)imageSnapshotFromText:(NSString*)text Color:(UIColor*)color Circle:(BOOL)circle TextAttributes:(NSDictionary*)attributes{
    CGFloat scale = [UIScreen mainScreen].scale;
    CGSize size = self.bounds.size;
    if (self.contentMode == UIViewContentModeScaleToFill || self.contentMode == UIViewContentModeScaleAspectFill || self.contentMode == UIViewContentModeScaleAspectFit || self.contentMode == UIViewContentModeRedraw){
        size.width  = floorf(size.width  * scale) / scale;
        size.height = floorf(size.height * scale) / scale;
    }
    UIGraphicsBeginImageContextWithOptions(size, NO, scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (circle) {
        CGPathRef path = CGPathCreateWithEllipseInRect(self.bounds, NULL);
        CGContextAddPath(context, path);
        CGContextClip(context);
        CGPathRelease(path);
    }
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
    CGSize textSize = [text sizeWithAttributes:attributes];
    CGRect bounds = self.bounds;
    [text drawInRect:CGRectMake(bounds.size.width/2 - textSize.width/2, bounds.size.height/2 - textSize.height/2, textSize.width, textSize.height) withAttributes:attributes];
    UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshot;
}
/// 浏览头像,点击全屏展示
- (void)kj_headerImageShowScreen{
    [self kj_headerImageShowScreenWithBackground:UIColor.blackColor];
}
- (void)kj_headerImageShowScreenWithBackground:(UIColor*)color{
    UIImage *image = self.image;
    CGFloat w = [UIScreen mainScreen].bounds.size.width;
    CGFloat h = [UIScreen mainScreen].bounds.size.height;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, w, h)];
    self.kOriginRect = [self convertRect:self.bounds toView:window];
    backgroundView.backgroundColor = color;
    backgroundView.alpha = 0;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.kOriginRect];
    imageView.image = image;
    imageView.tag = 552000;
    [backgroundView addSubview:imageView];
    [window addSubview:backgroundView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(kj_hideImage:)];
    [backgroundView addGestureRecognizer:tap];
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = CGRectMake(0,(h-image.size.height*w/image.size.width)/2, w, image.size.height*w/image.size.width);
        backgroundView.alpha = 1;
    } completion:^(BOOL finished) {
    }];
}
- (void)kj_hideImage:(UITapGestureRecognizer*)tap{
    UIView *backgroundView = tap.view;
    UIImageView *imageView = (UIImageView*)[tap.view viewWithTag:552000];
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = self.kOriginRect;
        backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [backgroundView removeFromSuperview];
    }];
}
- (CGRect)kOriginRect{
    return [objc_getAssociatedObject(self, @selector(kOriginRect)) CGRectValue];
}
- (void)setKOriginRect:(CGRect)kOriginRect{
    NSValue *rect = [NSValue valueWithCGRect:kOriginRect];
    objc_setAssociatedObject(self, @selector(kOriginRect), rect, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
@implementation UIImageViewLettersInfo
- (instancetype)init{
    if (self == [super init]) {
        self.color = [self randomColor];
        self.circle = YES;
        self.frist = YES;
        self.uppercase = YES;
        self.partition = @" ";
    }
    return self;
}
- (UIColor*)randomColor{
    srand48(arc4random());
    float red = 0.0;
    while (red < 0.1 || red > 0.84) {
        red = drand48();
    }
    float green = 0.0;
    while (green < 0.1 || green > 0.84) {
        green = drand48();
    }
    float blue = 0.0;
    while (blue < 0.1 || blue > 0.84) {
        blue = drand48();
    }
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
}
@end


备注:本文用到的部分函数方法和Demo,均来自三方库**KJEmitterView**,如有需要的朋友可自行pod 'KJEmitterView'引入即可


字母头像控件介绍就到此完毕,后面有相关再补充,写文章不容易,还请点个**小星星**传送门

相关文章
|
文字识别 算法 Swift
毕业设计在iOS上使用OpenCV实现图片中的文字框选文字识别
毕业设计在iOS上使用OpenCV实现图片中的文字框选文字识别
567 0
毕业设计在iOS上使用OpenCV实现图片中的文字框选文字识别
|
iOS开发
iOS开发-使用ShareSDK做分享如何让新浪分享后是可点击蓝色文字
iOS开发-使用ShareSDK做分享如何让新浪分享后是可点击蓝色文字
116 0
iOS开发-使用ShareSDK做分享如何让新浪分享后是可点击蓝色文字
|
iOS开发
iOS开发 - 同一段文字显示不同颜色和字体
iOS开发 - 同一段文字显示不同颜色和字体
112 0
|
iOS开发
iOS开发-调整文字之间间距
iOS开发-调整文字之间间距
292 0
|
iOS开发
iOS开发-同一段文字显示不同颜色
iOS开发-同一段文字显示不同颜色
101 0
|
程序员 API iOS开发
iOS开发:字符串设置指定内容的文字颜色、文字大小、文字字体类型
在iOS开发过程中,会有一些为了提高APP的视觉效果而设置的特别一点的效果,比如一行文字需要自定义不同的颜色和文字大小,这就用到通过富文本来设置字符串的颜色、大小和文字类型。这篇博文我打算只介绍怎么设置指定内容的一些文字属性设置,如果之前看过我写的博文,就会发现有一篇类似介绍通过富文本来设置字符串内容的博文,但是那篇是综合性的,包括介绍button的,以及UItextfield的设置,所以在这里我只介绍怎么设置字符串指定位置的一些自定义设置的方法,如有不妥之处,欢迎指正。
609 0
|
iOS开发
iOS tabbar文字不显示原因
iOS tabbar文字不显示原因
940 0
|
iOS开发
设计iOS中随系统键盘弹收和内容文字长度自适应高度的文本框
设计iOS中随系统键盘弹收和内容文字长度自适应高度的文本框
211 0
设计iOS中随系统键盘弹收和内容文字长度自适应高度的文本框
|
iOS开发
iOS中UIImageView用法总结
iOS中UIImageView用法总结
130 0
|
iOS开发
iOS UIImageView(图片)
UIImageView属性 1.Image 设置图片,默认显示 UIImageView *_imageView = [[UIImageView alloc]init]; _imageView.
1113 0