這兩天剛好項目上有一個頭像拼接的需求葬馋,想必做即時通訊的很多都有這樣的需求吧枕磁,所以就研究了一下微信的規(guī)則實現(xiàn)了一下沥邻。
效果如下
代碼
/**
頭像拼接
@param array 圖片數(shù)組
@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;
//最大列數(shù)
NSInteger max_col=3;
//最大行數(shù)
NSInteger max_row=3;
//列數(shù)
NSInteger column=ceil(count/2.0);
if(column>max_col)
column=max_col;
else if (column<1)
column=1;
//行數(shù)
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);
//每一行的列數(shù)
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)
{
//第一行的列數(shù)
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;
}
- 調(diào)用
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;