如何在iOS的var中存储UIImage的实例?

时间:2018-11-18 07:12:14

标签: ios swift uiimage

我在ViewControlller.swift中有一个过滤器功能,可以过滤photoImageView的图像,该图像也存储在ViewControlller.swift中。问题在于滤色器将应用于先前过滤的图像而不是原始图像的结果。如何将photoImageView存储在originalImage变量中以将过滤器应用于该变量?

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    //MARK: Properties
    @IBOutlet weak var photoImageView: UIImageView!

    @IBAction func slideFilter(_ sender: UISlider) {

        var hueFilter = Double(sender.value)
        hueFilter = hueFilter.rounded(toPlaces: 2)

        //create image to filter
        let inputImage = CIImage(image: photoImageView.image!)

        //Create a random color to apply
        let randomColor = [kCIInputAngleKey: hueFilter]

        //Apply filter to image
        let filteredImage = inputImage!.applyingFilter("CIHueAdjust", parameters: randomColor)     

        let renderImage = context.createCGImage(filteredImage, from: filteredImage.extent)

        // Reflect the change back in the interface
        photoImageView.image = UIImage(cgImage: renderImage!)
    }
}

当我尝试在ViewController中存储变量photoImageView的实例时,出现此错误Cannot use instance member 'photoImageView' within property initializer; property initializers run before 'self' is available

2 个答案:

答案 0 :(得分:1)

您不能在photoImageView中存储变量ViewController的实例。但是,您可以在photoImageView之类的方法中存储变量viewDidLoad()的实例。

只需在该行之后使用一个断点:

let inputImage = CIImage(image: photoImageView.image!)

查看inputImage的值是什么。这是您要操作的图像吗?

由于inputImage不正确,最终结果也会不正确。

希望对您有帮助。

答案 1 :(得分:0)

我明白了!

您只需在inputImage中任何方法之外创建ViewController变量。这样,任何方法都可以调用它。

inputImage(以及将要更改图像的任何位置)中为viewDidLoad()设置值。因此过滤器功能可以访问图像。

最终结果:

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    //MARK: Properties
    @IBOutlet weak var photoImageView: UIImageView!

    var inputImage:CIImage? 


    override func viewDidLoad() {
    super.viewDidLoad()
        inputImage = CIImage(image: photoImageView.image!)


    }


    @IBAction func slideFilter(_ sender: UISlider) {

        var hueFilter = Double(sender.value)
        hueFilter = hueFilter.rounded(toPlaces: 2)

        //Create a random color to apply
        let randomColor = [kCIInputAngleKey: hueFilter]

    //Apply filter to image
    let filteredImage = inputImage!.applyingFilter("CIHueAdjust", parameters: randomColor)     

    let renderImage = context.createCGImage(filteredImage, from: filteredImage.extent)

        // Reflect the change back in the interface
        photoImageView.image = UIImage(cgImage: renderImage!)
    }
}