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

时间:2014-12-13 07:57:47

标签: swift uiimageview uilabel

我尝试将文字添加到从用户处拍摄的图片中。

在第一个视图中,我创建了一个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)
}

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

但如何用文字保存图像?

我是否按照错误的方法获取输出? 任何人都可以帮我修理它。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

检查这个答案,它在Objective-c中,但我认为很容易移植这几行或使用它作为它 https://stackoverflow.com/a/4334902/2165337