仿微信群头像九宫格

+ (UIImage *)getGroupAvatarImageFormViewWithUserHeadIconImageList:(NSArray *)userHeadIconImageList andUserSexList:(NSArray *)userSexArr andHeight:(CGFloat)bgWH
{
    CGFloat padding = 2;
    CGFloat itemPadding = 1;
    
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bgWH, bgWH)];
    backgroundView.backgroundColor = [UIColor colorWithRed:225.0/255.0 green:225.0/255.0 blue:225.0/255.0 alpha:1.0];
    backgroundView.layer.cornerRadius = 4;
    backgroundView.layer.masksToBounds = YES;
    
    NSInteger userCount = userHeadIconImageList.count < 10 ? userHeadIconImageList.count : 9;
    NSInteger colNum = userCount < 2 ? 1 : userCount < 5 ? 2 : 3;
    NSInteger rowNum = userCount < 3 ? 1 : userCount < 7 ? 2 : 3;
    NSInteger maxColRow = MAX(colNum, rowNum);
    CGFloat itemWH = (bgWH - padding * 2 - (maxColRow - 1)*itemPadding) / maxColRow;
    CGFloat topPadding = (bgWH - itemWH * rowNum - itemPadding * (rowNum - 1)) / 2;
    
    for (NSInteger i = 0; i < userCount; i ++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        [imageView setFrame:CGRectMake(padding + (i % maxColRow) * (itemWH + itemPadding), topPadding + (i / maxColRow) * (itemWH + itemPadding), itemWH, itemWH)];
        if ((userSexArr.count == 3 && i == 2) || (userSexArr.count == 7 && i == 6)) {
            imageView.center = CGPointMake(bgWH/2, topPadding + (i / maxColRow) * (itemWH + itemPadding) + itemWH/2);
        }
        NSString *stringName ;
        if (userSexArr.count > i) {
            stringName = [NSString stringWithFormat:@"head_default%@",[userSexArr[i] intValue] == 0 ? @"5" : @"2"];
        }else {
            stringName = @"head_default5";
        }
        NSURL *headImageURL = [NSURL URLWithString:[Main_Url stringByAppendingString:userHeadIconImageList[i]]];
        [imageView sd_setImageWithURL:headImageURL placeholderImage:[UIImage imageNamed:stringName]];
        [backgroundView addSubview:imageView];
    }
    
    return [self renderInContextWithView:backgroundView];
}

你可能感兴趣的:(仿微信群头像九宫格)