ios - Converting UIImage to CGImage to get Pixel Color -


based on code question (how color of pixel in uiimage swift?), i'm trying run function when button gets tapped. here code far:

@iboutlet weak var graphimage: uiimageview!  var image : uiimage?  override func viewdidload() {     super.viewdidload()      // additional setup after loading view. }  func getpixelcolor(pos: cgpoint) -> uicolor {     var pixeldata = cgdataprovidercopydata(cgimagegetdataprovider(self.image!.cgimage))     var data : unsafepointer<uint8> = cfdatagetbyteptr(pixeldata)      var pixelinfo : int = ((int(image!.size.width) * int(pos.y) + int(pos.x)*4))      let r = cgfloat(data[pixelinfo])     let g = cgfloat(data[pixelinfo]+1)     let b = cgfloat(data[pixelinfo]+2)     let = cgfloat(data[pixelinfo]+3)      return uicolor(red: r, green: g, blue: b, alpha: a) }  @ibaction func playtapped(sender: anyobject) {     var c : cgfloat = 100.0     var d : cgfloat = 100.0     getpixelcolor(cgpoint(x:c,y:d)) } 

however, whenever tap play button in ios simulator, app crashes , warning "fatal error: unexpectedly found nil while unwrapping optional value" on first line of function getpixelcolor. doing wrong here/what need add?

pretty straight forward. based on code here, indeed unwrapping nil object. instance variable, image, never initialized anything... you're trying force unwrap ! nil.


Comments