iOS UIImageView文字頭像,首字母縮略頭像

前言

  • 提供類似於通訊錄頭像,支持漢字轉拼音,小寫轉大寫,分割等操作
  • 頭像瀏覽
GitHub地址:KJExtensionHandler

簡單介紹 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,均來自三方庫KJExtensionHandler,如有需要的朋友可自行pod 'KJExtensionHandler'引入即可

字母頭像控件介紹就到此完畢,後面有相關再補充,寫文章不容易,還請點個小星星傳送門

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章