#define HORIZONTAL_SPACE 30//水平間距
#define VERTICAL_SPACE ?8//豎直間距
#define CG_TRANSFORM_ROTATION ? (-M_PI_2 /2)//旋轉(zhuǎn)角度
/**
?*? 照片加水印
?*
*?@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],? //設(shè)置字體
?? ? ? ? ? ? ? ? ? ? ? ? ? NSForegroundColorAttributeName : [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.15]? //設(shè)置字體顏色
?? ? ? ? ? ? ? ? ? ? ? ? ? };
? ? NSMutableAttributedString ?*attrStr = [[NSMutableAttributedString alloc] initWithString:markText ?attributes:attr];
? ? CGFloat ?strWidth = attrStr.size.width;
? ? CGFloat ?strHeight = attrStr.size.height;
? ? //開(kāi)始旋轉(zhuǎn)上下文矩陣,繪制水印文字
? ? CGContextRef ?context = UIGraphicsGetCurrentContext();
? ? //將繪制原點(diǎn)(0,0)調(diào)整到原image的中心
? ? CGContextConcatCTM(context, CGAffineTransformMakeTranslation(w/2, h/2));
? ? //以繪制原點(diǎn)為中心旋轉(zhuǎn)
? ? CGContextConcatCTM(context, CGAffineTransformMakeRotation(CG_TRANSFORM_ROTATION));
? ? //將繪制原點(diǎn)恢復(fù)初始值,保證當(dāng)前context中心和源image的中心處在一個(gè)點(diǎn)(當(dāng)前context已經(jīng)旋轉(zhuǎn),所以繪制出的任何layer都是傾斜的)
? ? CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-w/2, -h/2));
? ? //? ? ? ? 計(jì)算需要繪制的列數(shù)和行數(shù)
?int ?horCount = sqrtLength / (strWidth +HORIZONTAL_SPACE) +1;
?int ?verCount = sqrtLength / (strHeight +VERTICAL_SPACE) +1;
? ? //? ? ? ? 此處計(jì)算出需要繪制水印文字的起始點(diǎn),由于水印區(qū)域要大于圖片區(qū)域所以起點(diǎn)在原有基礎(chǔ)上移
? ? CGFloat ?orignX = -(sqrtLength-w)/2;
? ? CGFloat ?orignY = -(sqrtLength-h)/2;
? ? CGFloat ?tempOrignX = orignX;
? ? //在每行繪制時(shí)Y坐標(biāo)疊加
? ? 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);
? ? ? ? }
? ? }
? ? //根據(jù)上下文制作成圖片
? ? UIImage ?*finalImg = UIGraphicsGetImageFromCurrentImageContext();
? ? UIGraphicsEndImageContext();
?return ?finalImg;
}