取得使用者當前位置(經緯度/地址)後,需將該文字資訊直接繪製到相片上,生成帶水印的新圖片,供分享或儲存。
- (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);
NSShadowAttributeName 讓文字在複雜背景下可讀。NSParagraphStyle 設定行距、對齊。UIImageOrientation,必要時先正規化再繪製。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)
}
}