這個(gè)功能前前后后很多細(xì)節(jié)致份,也饒了很多彎路变抽,最后核心功能總結(jié)如下。
一知举、添加圖片水铀猜佟(如添加公司logo)
也就是將兩張圖片合成,一張是需要添加的水印雇锡,一張是原圖片逛钻。
以下是添加水印代碼
image = [self addPrintImg:self.waterImgView.image toOriginImg:image andWithWMType:WMTypeWaterMark];
/**
* 繪制位圖
*
* @param print 將要添加的圖片
* @param Origin 原圖
*
* @return 已打好水印的圖片
*/
- (UIImage *)addPrintImg:(UIImage *)print toOriginImg:(UIImage *)Origin andWithWMType:(WMType)type
{
//繪制位圖的大小
UIGraphicsBeginImageContext(Origin.size);
//Draw Origin
[Origin drawInRect:CGRectMake(0, 0, Origin.size.width, Origin.size.height)];
//Draw print 將要添加水印的位置x、y和寬高(這里的寬高最好是設(shè)為原圖的寬高比锰提,以便適配各種像素)
[print drawInRect:CGRectMake(waterImg_x, waterImg_y, printWidth, printHeight)];
//返回的圖形大小
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
//end
UIGraphicsEndImageContext();
return resultImage;
}
二曙痘、添加動(dòng)態(tài)數(shù)據(jù)水印(如添加數(shù)字立肘、文字等)
以下是將動(dòng)態(tài)數(shù)據(jù)添加到圖片代碼
image = [self imageWithStringWaterMark:@"我是文字" atPoint:CGPointMake(x,y) atFont:[UIFont fontWithName:@"Marker Felt" size:20.f] andImg:image];
/**
*
* @param markString 將要添加的文字
* @param point 將要添加的文字在圖片上的位置
* @param font 文字大小
* @param image 將要添加文字的圖片
*
* @return 已打好水印的圖片
*/
- (UIImage *)imageWithStringWaterMark:(NSString *)markString atPoint:(CGPoint)point atFont:(UIFont*)font andImg:(UIImage *)image
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)
{
UIGraphicsBeginImageContextWithOptions([image size], NO, 0.0); // 0.0 for scale means "scale for device's main screen".
}
#else
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 4.0)
{
UIGraphicsBeginImageContext([image size]);
}
#endif
// 繪制文字
//文字顏色
UIColor *magentaColor = [UIColor whiteColor];
[magentaColor set];
//原圖
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
//文字類型
UIFont *helveticaBold = font;
//水印文字
[markString drawInRect:CGRectMake(point.x, point.y, image.size.width, image.size.height)
withAttributes:@{NSFontAttributeName: helveticaBold,
NSForegroundColorAttributeName: magentaColor
}];
//返回新的圖片
UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newPic;
}
效果圖:
如有不妥之處望能指正谅年!