首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 將文字繪製到圖片上:為照片添加位置水印的完整實作

     編輯:程式設計綜合問答

需求場景

取得使用者當前位置(經緯度/地址)後,需將該文字資訊直接繪製到相片上,生成帶水印的新圖片,供分享或儲存。

核心實作:UIImage 繪圖上下文

- (UIImage *)imageByAddingText:(NSString *)text 
                       toImage:(UIImage *)sourceImage 
                    atPoint:(CGPoint)point 
                  fontSize:(CGFloat)fontSize 
                   textColor:(UIColor *)color {
    // 1. 開啟繪圖上下文,尺寸與原圖一致
    UIGraphicsBeginImageContextWithOptions(sourceImage.size, NO, sourceImage.scale);
    
    // 2. 繪製原圖
    [sourceImage drawAtPoint:CGPointZero];
    
    // 3. 設定文字屬性
    NSDictionary *attrs = @{
        NSFontAttributeName: [UIFont systemFontOfSize:fontSize],
        NSForegroundColorAttributeName: color,
        NSParagraphStyleAttributeName: [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy]
    };
    
    // 4. 計算文字繪製矩形(支援換行、對齊)
    CGRect textRect = [text boundingRectWithSize:CGSizeMake(sourceImage.size.width - point.x * 2, CGFLOAT_MAX)
                                         options:NSStringDrawingUsesLineFragmentOrigin
                                      attributes:attrs
                                         context:nil];
    textRect.origin = point;
    
    // 5. 繪製文字
    [text drawInRect:textRect withAttributes:attrs];
    
    // 6. 取得結果並結束上下文
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

使用範例

// 取得位置字串(假設已經透過 CLGeocoder 反地理編碼)
NSString *locationText = @"台北市信義區市府路 45 號\n2024-05-15 14:30";

// 繪製:左上角邊距 20pt,字體 24pt,白色半透明
UIImage *watermarked = [self imageByAddingText:locationText
                                      toImage:originalImage
                                   atPoint:CGPointMake(20, 20)
                                 fontSize:24
                                  textColor:[UIColor colorWithWhite:1 alpha:0.8]];

// 儲存至相簿
UIImageWriteToSavedPhotosAlbum(watermarked, nil, nil, nil);

進階優化方向

  1. 陰影/描邊:在 attrs 加入 NSShadowAttributeName 讓文字在複雜背景下可讀。
  2. 多行自動換行:使用 NSParagraphStyle 設定行距、對齊。
  3. 高效能批量處理:大量圖片時改用 Core Graphics / Metal 避免主執行緒阻塞。
  4. 支援旋轉方向:注意 UIImageOrientation,必要時先正規化再繪製。

Swift 版本速查

func addText(_ text: String, to image: UIImage, at point: CGPoint, fontSize: CGFloat, color: UIColor) -> UIImage {
    let format = UIGraphicsImageRendererFormat.default()
    format.scale = image.scale
    let renderer = UIGraphicsImageRenderer(size: image.size, format: format)
    return renderer.image { ctx in
        image.draw(at: .zero)
        let attrs: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: fontSize),
            .foregroundColor: color
        ]
        text.draw(at: point, withAttributes: attrs)
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved