如何将从用户拍摄的文字添加到图像?

问题描述:

我正在试图将文本添加到从用户获取的图像中。如何将从用户拍摄的文字添加到图像?

在第一个视图中,我创建了一个textField和一个按钮。无论用户在textField中输入什么内容,然后按下按钮,它都会进入第二个视图,其中有图像视图,我可以使用UIImagePickerController设置图像。

我在第二个视图中有一个标签,其文本设置为textField.text

我可以在任何我想要的地方拖动该标签。

代码如下:

class SecondView: UIViewController, UINavigationControllerDelegate,UIImagePickerControllerDelegate { 

@IBOutlet weak var imageView: UIImageView! 

var theLabel : UILabel! 
var theText = "" 
override func viewDidLoad() { 
    super.viewDidLoad() 
    theLabel = UILabel(frame: CGRect(x: self.view.bounds.width/2 - 100, y: self.view.bounds.height/2 - 50, width: 200, height: 100)) 
    theLabel.textAlignment = NSTextAlignment.Center 
    self.view.addSubview(theLabel) 
    var gesture = UIPanGestureRecognizer(target: self, action: Selector("dragMe:")) 
    theLabel.addGestureRecognizer(gesture) 
    theLabel.userInteractionEnabled = true 
    theLabel.text = theText 
} 
func dragMe(gesture : UIPanGestureRecognizer) { 
    let translation = gesture.translationInView(self.view) 
    var label = gesture.view! 
    label.center = CGPoint(x: label.center.x + translation.x, y: label.center.y + translation.y) 
    gesture.setTranslation(CGPointZero, inView: self.view) 
} 
@IBAction func pickAnImage(sender: AnyObject) { 
    var imagePicker = UIImagePickerController() 
    imagePicker.delegate = self 
    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary 
    self.presentViewController(imagePicker, animated: true, completion: nil) 
} 
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { 
    imageView.image = image 
    var bool = true 
    self.dismissViewControllerAnimated(bool, completion: nil) 
} 

现在我想将标签添加到图像。由于我可以将标签拖动到任何位置,因此可以将其放置在图像上。

但如何保存与文本的图像?

我按照错误的方法得到输出? 任何人都可以帮我解决它。

您需要设置一个CGContext并从旧的加上渲染的文本创建一个新的图像。见https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/index.html

+0

嗨,感谢您的答复。能够设置上下文并从旧创建新图像,但无法呈现文本。你能告诉我如何获得文本。我没有得到使用哪个函数来呈现文本。请帮帮我!!!提前致谢 – 2014-12-14 03:36:03

检查这个答案,它是用Objective-C,但我认为这是容易移植的这几行,或者使用它,因为它是 https://*.com/a/4334902/2165337