将相机胶卷图像导入UIView背景

时间:2015-07-17 14:05:11

标签: ios iphone swift uiview

一个小小的警告:我在swift

完成了一个完整的菜鸟

我正在创建一个小应用程序(最终将允许用户)在iPhone上绘制他们从相机胶卷中选择的图像。但是,我在将图像设置为UIView(drawView)的背景时遇到了一些麻烦。有人可以给我一些关于如何解决这个问题的建议吗?我拼凑的代码如下所示。

我的ViewController文件:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate,     UINavigationControllerDelegate {

@IBOutlet var drawView : AnyObject!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    imagePicker.delegate = self

@IBAction func clearTapped() {
    var theDrawView: DrawView = drawView as! DrawView

    theDrawView.lines = []
    theDrawView.setNeedsDisplay()
}

let imagePicker = UIImagePickerController()

@IBAction func importImage(sender: AnyObject) {


    imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
    imagePicker.allowsEditing = true
    self.presentViewController(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        drawView.backgroundImage = pickedImage

    }

    func dismissViewControllerAnimated(true, completion: nil)

}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    dismissViewControllerAnimated(true, completion: nil)
}


}


}

另外,我的drawView有一个单独的swift文件,用于处理用户如何在其中绘制线条。

1 个答案:

答案 0 :(得分:0)

您希望将代码分开一点。现在,您似乎正在尝试在控制器中创建控制器。实现一个类,它是UIIMagePickerController的子类,带有必要的委托(你已经有了代码,所以只需要复制和粘贴):

class MyImagePicker: UIImagePickerController, UIImagePickerControllerDelegate {

}

然后在视图控制器中初始化图像选择器:

let myImagePicker = MyImagePicker()

调用正确的方法返回图像,将UIView的背景图像设置为该图像,然后将该视图添加为子视图:

drawView.backgroundImage = pickedImage
self.addSubview(pickedImage)
希望有效!