UIImage添加水印

// UIImage扩展,用于添加水印
extension UIImage {
    func addVideoWatermark(_ watermarkView: UIView, targetFrame: CGRect) -> UIImage? {
        // 将UIView转换为UIImage
        let watermarkImage = watermarkView.convertToImage()

        // 开始图片上下文
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        defer { UIGraphicsEndImageContext() }

        // 绘制原始图片
        draw(in: CGRect(origin: .zero, size: size))

        // 计算水印在目标帧中的大小和位置
        let watermarkSize = watermarkImage.size
        let targetSize = targetFrame.size

        // 计算缩放比例
        let scaleX = targetSize.width / watermarkSize.width
        let scaleY = targetSize.height / watermarkSize.height
        let scale = min(scaleX, scaleY)

        // 计算缩放后的水印大小
        let scaledSize = CGSize(width: watermarkSize.width * scale, height: watermarkSize.height * scale)

        // 计算水印位置(居中于目标帧)
        let x = targetFrame.origin.x + (targetFrame.size.width - scaledSize.width) / 2
        let y = targetFrame.origin.y + (targetFrame.size.height - scaledSize.height) / 2

        // 绘制水印
        watermarkImage.draw(in: CGRect(x: x, y: y, width: scaledSize.width, height: scaledSize.height))

        // 获取合成后的图片
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

extension UIView {
    func convertToImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
        defer { UIGraphicsEndImageContext() }
        if let context = UIGraphicsGetCurrentContext() {
            layer.render(in: context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            return image ?? UIImage()
        }
        return UIImage()
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容