这两天刚好项目上有一个头像拼接的需求,想必做即时通讯的很多都有这样的需求吧,所以就研究了一下微信的规则实现了一下。
效果如下
代码
/**
头像拼接
@param array 图片数组
@param size 图片大小
@param cornerRadius 圆角半径
@return <#return value description#>
*/
-(UIImage *)imageCompose:(NSArray *)array size:(CGSize)size cornerRadius:(CGFloat)cornerRadius
{
if(array.count)
{
//开启一个图片上下文
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale) ;
//添加裁剪路径
UIBezierPath *clippath=[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) cornerRadius:cornerRadius];
[clippath addClip];
//绘制背景矩形
UIBezierPath *path=[UIBezierPath bezierPathWithRect:CGRectMake(0, 0, size.width, size.height)];
[[UIColor lightGrayColor] setFill];
[path fill];
NSInteger count=array.count;
if(count>9)
count=9;
//最大列数
NSInteger max_col=3;
//最大行数
NSInteger max_row=3;
//列数
NSInteger column=ceil(count/2.0);
if(column>max_col)
column=max_col;
else if (column<1)
column=1;
//行数
NSInteger row=ceil(count/(CGFloat)column);
if(row>max_row)
row=max_row;
if(row<1)
row=1;
//每个头像间的间距
CGFloat margin=2;
CGFloat imgsize=(size.width-(MAX(column, row)+1)*margin)/MAX(column, row);
//每一行的列数
NSInteger rowcount=ceil(count/(CGFloat)row);
NSInteger k=0;
for (int i =0; i<row; i++) {
CGFloat rowmargin=(size.height-imgsize*row-margin*(MAX(row-1, 1)))/(CGFloat)row;
//每一行的y值
CGFloat y=i*imgsize+(i+1)*rowmargin;
if(i>0)
y=rowmargin+i*imgsize+i*margin;
if(count<row*column&&i==0)
{
//第一行的列数
NSInteger count1=rowcount-(row*column-count);
CGFloat margin1=(size.width-imgsize*count1-margin*MAX(count1-1, 1))/2.0;
for (int j=0; j<count1; j++) {
UIImage *img=array[k];
CGFloat x=margin1;
if(j>0)
x=margin1+j*imgsize+j*margin;
[img drawInRect:CGRectMake(x,y, imgsize, imgsize)];
k++;
}
}
else
{
CGFloat margin1=(size.width-imgsize*rowcount)/(rowcount+1);
for (int j=0; j<rowcount; j++) {
UIImage *img=array[k];
[img drawInRect:CGRectMake(j*imgsize+(j+1)*margin1, y, imgsize, imgsize)];
k++;
}
}
}
UIImage *newimge=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimge;
}
return nil;
}
- 调用
NSMutableArray *imgs=[NSMutableArray array];
[imgs addObject:[UIImage imageNamed:@"al1.jpg"]];
[imgs addObject:[UIImage imageNamed:@"al2.jpg"]];
[imgs addObject:[UIImage imageNamed:@"al3.jpg"]];
[imgs addObject:[UIImage imageNamed:@"al4.jpg"]];
[imgs addObject:[UIImage imageNamed:@"al5.jpg"]];
[imgs addObject:[UIImage imageNamed:@"al6.jpg"]];
[imgs addObject:[UIImage imageNamed:@"al7.jpg"]];
[imgs addObject:[UIImage imageNamed:@"al8.jpg"]];
[imgs addObject:[UIImage imageNamed:@"al9.jpg"]];
UIImage *img=[self imageCompose:imgs size:CGSizeMake(100, 100) cornerRadius:10];
self.imgv.image=img;