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

2020-11-23  本文已影响0人  弹吉他的少年

前言

GitHub地址:KJCategories

简单介绍 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,均来自三方库KJCategories,如有需要的朋友可自行pod 'KJCategories'引入即可

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

上一篇下一篇

猜你喜欢

热点阅读