美文网首页
给图片添加水印

给图片添加水印

作者: adalillian | 来源:发表于2020-05-26 18:53 被阅读0次

    此文章为转载, 原文地址: https://www.jianshu.com/p/280dbe07d3fd

    加水印的方式有很多,比如给图片添加图片水印、文字水印,或者给视频添加图片水印、文字水印。本文首先讲解如何给图片添加文字水印、图片水印,即图文合成和图片合成效果。

    一、给图片添加文字水印

    // 给图片添加文字水印:+ (UIImage*)jx_WaterImageWithImage:(UIImage*)image text:(NSString*)text textPoint:(CGPoint)point attributedString:(NSDictionary* )attributed{//1.开启上下文UIGraphicsBeginImageContextWithOptions(image.size,NO,0);//2.绘制图片[image drawInRect:CGRectMake(0,0, image.size.width, image.size.height)];//添加水印文字[text drawAtPoint:point withAttributes:attributed];//3.从上下文中获取新图片UIImage* newImage =UIGraphicsGetImageFromCurrentImageContext();//4.关闭图形上下文UIGraphicsEndImageContext();//返回图片returnnewImage;}

    二、给图片添加图片水印

    给图片添加图片水印,这里提供两种方法,以供参考。

    方法一

    // 给图片添加图片水印+ (UIImage*)jx_WaterImageWithImage:(UIImage*)image waterImage:(UIImage*)waterImage waterImageRect:(CGRect)rect{//1.获取图片//2.开启上下文UIGraphicsBeginImageContextWithOptions(image.size,NO,0);//3.绘制背景图片[image drawInRect:CGRectMake(0,0, image.size.width, image.size.height)];//绘制水印图片到当前上下文[waterImage drawInRect:rect];//4.从上下文中获取新图片UIImage* newImage =UIGraphicsGetImageFromCurrentImageContext();//5.关闭图形上下文UIGraphicsEndImageContext();//返回图片returnnewImage;}

    方法二

    1、新建类别UIImage+LL继承自UIImage

    /**

    *  UIImage+LL.h

    */#import<UIKit/UIKit.h>@interfaceUIImage(LL)/**

    *  打水印

    *

    *  @param backgroundImage  背景图片

    *  @param markName 右下角的水印图片

    */+ (instancetype)waterMarkWithImageName:(NSString*)backgroundImage andMarkImageName:(NSString*)markName;@end

    2、UIImage+LL.m中配置图片合成的代码

    /**

    *  UIImage+LL.m

    */#import"UIImage+LL.h"@implementationUIImage(LL)+ (instancetype)waterMarkWithImageName:(NSString*)backgroundImage andMarkImageName:(NSString*)markName{UIImage*bgImage = [UIImageimageNamed:backgroundImage];UIGraphicsBeginImageContextWithOptions(bgImage.size,NO,0.0);    [bgImage drawInRect:CGRectMake(0,0, bgImage.size.width, bgImage.size.height)];UIImage*waterImage = [UIImageimageNamed:markName];CGFloatscale =0.3;CGFloatmargin =5;CGFloatwaterW = waterImage.size.width * scale;CGFloatwaterH = waterImage.size.height * scale;CGFloatwaterX = bgImage.size.width - waterW - margin;CGFloatwaterY = bgImage.size.height - waterH - margin;        [waterImage drawInRect:CGRectMake(waterX, waterY, waterW, waterH)];UIImage*newImage =UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnnewImage;}@end

    3、背景图片右下角添加水印图片

    /**

            *  这个方法只需要传入一个需要被打水印的图片名字和一个水印图标的名字就可以自动合成水印图片

            */UIImage*image = [UIImagewaterMarkWithImageName:@"bg.jpeg"andMarkImageName:@"logo"];        _imageView.image = image;

    相关文章

      网友评论

          本文标题:给图片添加水印

          本文链接:https://www.haomeiwen.com/subject/lunqjqtx.html