我使用SO POST的答案在圖像上繪製文字。我遇到的問題是當CGPoint設置在圖像的右邊緣附近時,文本從圖像延伸出來。我試圖找出一種方法來從CGPoint中繪製左側而不是右側,或者以某種方式計算將繪製的文本的點的大小,然後移動繪製點以適應該大小。從圖像上延伸出的圖像上的文字繪製
這是我使用的代碼。
func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let color = UserDefaults.standard.colorForKey(key: "color")!
let font = UserDefaults.standard.value(forKey: "font") as! String
let size = UserDefaults.standard.value(forKey: "size") as! Int
let fontAndSize = UIFont(name: font, size: CGFloat(size))!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSFontAttributeName: fontAndSize,
NSForegroundColorAttributeName: color,
] as [String : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let mediaType = info[UIImagePickerControllerMediaType] as? String {
if mediaType.isEqual((kUTTypeImage as String)) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
let width = pickedImage.size.width
let height = pickedImage.size.height
// this puts the point in the bottom right of the image which then causes the text drawn to extend off of the image
let point = CGPoint(x: width - 20, y: height - 50)
let timestampText = getTimestampText() as NSString
let timestampImage = textToImage(drawText: timestampText, inImage: pickedImage, atPoint: point)
if newMedia {
UIImageWriteToSavedPhotosAlbum(timestampImage, nil, nil, nil)
}
}
謝謝!這工作。我也想弄清楚如何在中心畫畫。爲此,我將rect屬性修改爲:let rect = CGRect(x:point.x-(rectSize.width/2),y:point.y,width:rectSize.width,height:rectSize.height)。這給了我正確的x位置,但是y位置不是完全居中,而是位於圖像中央下方。有關爲什麼它不完全居中的任何建議? – chickenparm
沒關係!我改變它讓rect = CGRect(x:point.x-(rectSize.width/2),y:point.y-(rectSize.height/2),width:rectSize.width,height:rectSize.height)和這是工作。 – chickenparm
@chickenparm很高興聽到:) –