iOS | 图片打水印

这个功能前前后后很多细节,也饶了很多弯路,最后核心功能总结如下。

一、添加图片水印(如添加公司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和宽高(这里的宽高最好是设为原图的宽高比,以便适配各种像素)
    [print drawInRect:CGRectMake(waterImg_x, waterImg_y, printWidth, printHeight)];
        
    //返回的图形大小
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //end
    UIGraphicsEndImageContext();
    
    return resultImage;
}

二、添加动态数据水印(如添加数字、文字等)

以下是将动态数据添加到图片代码

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;
}

效果图:

iOS | 图片打水印_第1张图片
背景图+(水印)簇格运动logo图片+(水印)13.69KM数字或文字

如有不妥之处望能指正!

你可能感兴趣的:(iOS | 图片打水印)