You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift项目:如何实现UIImage多行重复旋转水印

实现UIImage多行重复旋转水印的Swift方案

以下是实现多行重复式45度旋转水印的完整代码,替换你现有的addWatermark方法即可:

private func addRepeatWatermark(_ text: String, to image: UIImage) -> UIImage? {
    let renderer = UIGraphicsImageRenderer(size: image.size)
    let watermarkedImage = renderer.image { context in
        // 先绘制原始图片
        image.draw(at: .zero)
        
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont(name: "Inter", size: 50 * 3)!,
            .foregroundColor: UIColor(red: 0.58, green: 0.64, blue: 0.72).withAlphaComponent(0.5)
        ]
        let textSize = text.size(withAttributes: attributes)
        
        // 计算45度旋转后文本的占位尺寸(菱形的对角线长度)
        let rotatedTextWidth = textSize.width * cos(CGFloat.pi/4) + textSize.height * sin(CGFloat.pi/4)
        let rotatedTextHeight = textSize.width * sin(CGFloat.pi/4) + textSize.height * cos(CGFloat.pi/4)
        
        // 设置水印之间的间距(可根据需求调整)
        let spacing: CGFloat = 80
        
        // 计算需要绘制的行数和列数,确保铺满整个图片
        let totalWidth = image.size.width + rotatedTextWidth + spacing
        let totalHeight = image.size.height + rotatedTextHeight + spacing
        let columnCount = Int(totalWidth / (rotatedTextWidth + spacing)) + 1
        let rowCount = Int(totalHeight / (rotatedTextHeight + spacing)) + 1
        
        // 循环绘制每个水印
        for row in 0..<rowCount {
            for column in 0..<columnCount {
                // 计算当前水印的基础位置
                let x = column * Int(rotatedTextWidth + spacing) - Int(rotatedTextWidth)
                let y = row * Int(rotatedTextHeight + spacing) - Int(rotatedTextHeight)
                
                // 保存当前上下文状态
                context.cgContext.saveGState()
                
                // 平移到水印中心位置,然后旋转45度
                let centerX = CGFloat(x) + rotatedTextWidth / 2
                let centerY = CGFloat(y) + rotatedTextHeight / 2
                context.cgContext.translateBy(x: centerX, y: centerY)
                context.cgContext.rotate(by: CGFloat.pi / 4)
                context.cgContext.translateBy(x: -textSize.width / 2, y: -textSize.height / 2)
                
                // 绘制文本
                text.draw(at: .zero, withAttributes: attributes)
                
                // 恢复上下文状态
                context.cgContext.restoreGState()
            }
        }
    }
    return watermarkedImage
}

关键改动说明

  • 旋转尺寸计算:通过三角函数算出45度旋转后文本的实际占位范围,确保重复排列时不会重叠或出现空隙
  • 网格布局逻辑:计算需要的行列数,覆盖超出图片边界的区域,保证水印铺满整个画面
  • 上下文状态管理:每次绘制单个水印前保存上下文状态,绘制后恢复,避免旋转影响后续绘制
  • 间距可调:spacing变量可以根据需求调整水印之间的距离,控制密度

你可以根据实际需求调整字体大小、透明度、间距等参数,达到预期的水印效果。

内容的提问来源于stack exchange,提问作者Rin Star

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 02:20:25