如何使用此代码在图像上添加水印? [英] How can I add a watermark to an image using this code?

查看:193
本文介绍了如何使用此代码在图像上添加水印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道还有其他几种方法可以做到这一点;我不想导入任何不需要的东西.如果有人可以帮助我编写代码,那就太好了.

I know there are several other ways to do this; I don't want to import anything that I don't need to. If someone can help me with his code, that would be great.

当前,它仅保存原始图像而没有水印图像.

Currently, it is only saving the original image without the watermark image.

extension UIImage {

    class func imageWithWatermark(image1: UIImageView, image2: UIImageView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(image1.bounds.size, false, 0.0)
        image2.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        image1.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

func addWatermark() {
    let newImage = UIImage.imageWithWatermark(imageView, image2: watermarkImageView)
    UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)
}

我的水印出现在保存的图像上.

I've got the watermark appearing on the saved images.

我不得不切换图层的顺序:

I had to switch the order of the layers:

 image1.layer.renderInContext(UIGraphicsGetCurrentContext()!)
 image2.layer.renderInContext(UIGraphicsGetCurrentContext()!)

但是,它没有出现在正确的位置.它似乎总是出现在图像的中央.

HOWEVER, it is not appearing in the correct place.It seems to always appear in the center of the image.

推荐答案

如果获取UIImageViews的图像,则可以使用以下概念:

If you grab the UIImageViews' images you could use the following concept:

if let img = UIImage(named: "image.png"), img2 = UIImage(named: "watermark.png") {

    let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)

    UIGraphicsBeginImageContextWithOptions(img.size, true, 0)
    let context = UIGraphicsGetCurrentContext()

    CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
    CGContextFillRect(context, rect)

    img.drawInRect(rect, blendMode: .Normal, alpha: 1)
    img2.drawInRect(CGRectMake(x,y,width,height), blendMode: .Normal, alpha: 1)

    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    UIImageWriteToSavedPhotosAlbum(result, nil, nil, nil)

}

这篇关于如何使用此代码在图像上添加水印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆