美文网首页iOS Developer
给图片添加文字水印,可直接返回image

给图片添加文字水印,可直接返回image

作者: timeforasong | 来源:发表于2017-04-21 11:11 被阅读22次

///将label画成image

- (UIImage *)imageWithLogoText:(UIImage *)img
                          text:(NSString *)text1
                        string:(NSString *)text2
                        str:(NSString *)text3
{
    
    CGSize size = CGSizeMake(img.size.width, img.size.height);          //设置上下文(画布)大小
    UIGraphicsBeginImageContext(size);                       //创建一个基于位图的上下文(context),并将其设置为当前上下文
    CGContextRef contextRef = UIGraphicsGetCurrentContext(); //获取当前上下文
    CGContextTranslateCTM(contextRef, 0, img.size.height);   //画布的高度
    CGContextScaleCTM(contextRef, 1.0, -1.0);                //画布翻转
    CGContextDrawImage(contextRef, CGRectMake(0, 0, img.size.width, img.size.height), [img CGImage]);  //在上下文种画当前图片
    
    //上下文种的文字属性
    CGContextTranslateCTM(contextRef, 0, img.size.height);
    CGContextScaleCTM(contextRef, 1.0, -1.0);
    [text1 drawInRect:CGRectMake(35, 30, img.size.width, 200) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:64],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [text2 drawInRect:CGRectMake(35, (img.size.height/2) - 100, img.size.width, 200) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:64],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [text3 drawInRect:CGRectMake(35, img.size.height - 100, img.size.width, 200) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:48],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    UIImage *targetimg =UIGraphicsGetImageFromCurrentImageContext();  //从当前上下文种获取图片
    UIGraphicsEndImageContext();                            //移除栈顶的基于当前位图的图形上下文。
    return targetimg;
}

相关文章

网友评论

    本文标题:给图片添加文字水印,可直接返回image

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