#define HORIZONTAL_SPACE 30//水平间距
#define VERTICAL_SPACE 8//竖直间距
#define CG_TRANSFORM_ROTATION (-M_PI_2 /2)//旋转角度
/**
* 照片加水印
*
* @param img 需要加水印的照片
* @param markText 需要加上去的文字
*
* @return 加好文字的照片
*/
-(UIImage*) watermarkImage:(UIImage*)img withName:(NSString*) markText
{
int w = img.size.width;
int h = img.size.height;
UIGraphicsBeginImageContext(img.size);
CGFloat sqrtLength =sqrt(w*w + h*h);
[img drawInRect:CGRectMake(0,0, w, h)];
NSDictionary *attr = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:20], //设置字体
NSForegroundColorAttributeName : [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.15] //设置字体颜色
};
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:markText attributes:attr];
CGFloat strWidth = attrStr.size.width;
CGFloat strHeight = attrStr.size.height;
//开始旋转上下文矩阵,绘制水印文字
CGContextRef context = UIGraphicsGetCurrentContext();
//将绘制原点(0,0)调整到原image的中心
CGContextConcatCTM(context, CGAffineTransformMakeTranslation(w/2, h/2));
//以绘制原点为中心旋转
CGContextConcatCTM(context, CGAffineTransformMakeRotation(CG_TRANSFORM_ROTATION));
//将绘制原点恢复初始值,保证当前context中心和源image的中心处在一个点(当前context已经旋转,所以绘制出的任何layer都是倾斜的)
CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-w/2, -h/2));
// 计算需要绘制的列数和行数
int horCount = sqrtLength / (strWidth +HORIZONTAL_SPACE) +1;
int verCount = sqrtLength / (strHeight +VERTICAL_SPACE) +1;
// 此处计算出需要绘制水印文字的起始点,由于水印区域要大于图片区域所以起点在原有基础上移
CGFloat orignX = -(sqrtLength-w)/2;
CGFloat orignY = -(sqrtLength-h)/2;
CGFloat tempOrignX = orignX;
//在每行绘制时Y坐标叠加
CGFloat tempOrignY = orignY;
for(inti =0; i < horCount * verCount; i++) {
[markText drawInRect:CGRectMake(tempOrignX, tempOrignY, strWidth, strHeight) withAttributes:attr];
if(i % horCount ==0 && i !=0) {
tempOrignX = orignX;
tempOrignY += (strHeight +VERTICAL_SPACE);
}else{
tempOrignX += (strWidth +HORIZONTAL_SPACE);
}
}
//根据上下文制作成图片
UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return finalImg;
}
网友评论