如果只是打简单的一样文字或者几行问题,可以直接在画布
//以原图的图大小为画布创建上下文
UIGraphicsBeginImageContext(image.size)
内直接画上文字。
如果是稍微复杂的比如 图片和 文字组合的水印。也可以直接画但是位置结算麻烦。推荐先把水印的布局写出来一个view然后用view生成图片,再把图片合成到原图上。
view生成图片的方法(该方法只能在主线程使用,否则会crash):
#pragma mark 生成image
+ (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size{
//下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
打水印方法
/// 水印合成
/// @param image 原图
/// @param waterModel 水印model
+(UIImage *)putWaterImageWith:(UIImage *)image waterModel:(WaterModel*)waterModel{
//以原图的图大小为底图
CGFloat w1 = image.size.width;
CGFloat h1 = image.size.height;
CGFloat contextH;
if (h1 > w1) {
contextH = h1 * (120 / APP_HEIGHT);
}else{
contextH = w1 * (120 / APP_HEIGHT);
}
WaterView *view = [[WaterView alloc] initWithImageSize:image.size frame:CGRectMake(0, 0, w1, contextH) waterModel:waterModel];
[view layoutIfNeeded];
UIImage *waterImage = [GetWaterImage makeImageWithView:view withSize:CGSizeMake(w1, view.height)];
CGFloat h = waterImage.size.height;
//以原图的图大小为画布创建上下文
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0, 0, w1, h1)];//先把1.png 画到上下文中
[waterImage drawInRect:CGRectMake(0, h1-h, w1, h)];//再把小图放在上下文中
UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();//从当前上下文中获得最终图片
UIGraphicsEndImageContext();//关闭上下文
return resultImg;
}
这里用图片的长宽 比较 大的 一个 作为 水印高度的锚定点,以适配不同尺寸图片。
WaterView 内部计算自己的缩放比例:
self.scal = 1;
self.scal = frame.size.width / APP_WIDTH;
if (size.width > size.height) {
self.scal = size.height / APP_WIDTH;
}
WaterView 内部计算自己的尺寸:
CGFloat addressBottom = self.addressLb.bottom;
CGSize tagSize = [self.tagsLb.text sizeForFont:self.tagsLb.font maxWidth:CGSizeMake(self.width - 2*margin, 100)];
self.height = tagSize.height + addressBottom + 2 * margin;
然后用渲染后的 WaterView的高度和宽度 生成图片。最后合成到原图上,位置可自己设定。这样水印图片可适配所有尺寸图片。
如果涉及到图片压缩,建议先压缩在打水印,这样水印不会模糊。