2015-05-12 113 views
0

目標:從正確的位置從imagePickerController獲取更大的編輯圖像。CGImageCreateWithImageInRect與UIImagePickerControllerOriginalImage不能很好地工作

問題:任何人都可以請幫助我得到圖像,並告訴我我的代碼是錯誤的嗎?在我的調查中,CGImageCreateWithImageInRectUIImagePickerControllerCropRect看起來很奇怪。但不知道......

爲什麼信息[UIImagePickerControllerEditedImage]太小了,所以我想用信息[UIImagePickerControllerEditedImage]

問題裁剪圖像在代碼中返回錯誤的位置編輯圖像。

其他信息:原始圖像旋轉90°,所以我用imageRotatedByDegrees功能在網絡上找到,而且效果很好。

class PhotoViewController: UIImagePickerControllerDelegate { 
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { 

      let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage 
      let rotatedOriginalImage = originalImage!.imageRotatedByDegrees(90, flip: false) 
      let croppedImage = UIImage(CGImage: CGImageCreateWithImageInRect(rotatedOriginalImage.CGImage, info[UIImagePickerControllerCropRect]!.CGRectValue())) 
    } 
} 


// For rotating UIImagePickerControllerOriginalImage 
// source: http://blog.ruigomes.me/how-to-rotate-an-uiimage-using-swift/ 
extension UIImage { 
    public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage { 
     let radiansToDegrees: (CGFloat) -> CGFloat = { 
      return $0 * (180.0/CGFloat(M_PI)) 
     } 
     let degreesToRadians: (CGFloat) -> CGFloat = { 
      return $0/180.0 * CGFloat(M_PI) 
     } 

     // calculate the size of the rotated view's containing box for our drawing space 
     let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size)) 
     let t = CGAffineTransformMakeRotation(degreesToRadians(degrees)); 
     rotatedViewBox.transform = t 
     let rotatedSize = rotatedViewBox.frame.size 

     // Create the bitmap context 
     UIGraphicsBeginImageContext(rotatedSize) 
     let bitmap = UIGraphicsGetCurrentContext() 

     // Move the origin to the middle of the image so we will rotate and scale around the center. 
     CGContextTranslateCTM(bitmap, rotatedSize.width/2.0, rotatedSize.height/2.0); 

     // // Rotate the image context 
     CGContextRotateCTM(bitmap, degreesToRadians(degrees)); 

     // Now, draw the rotated/scaled image into the context 
     var yFlip: CGFloat 

     if(flip){ 
      yFlip = CGFloat(-1.0) 
     } else { 
      yFlip = CGFloat(1.0) 
     } 

     CGContextScaleCTM(bitmap, yFlip, -1.0) 
     CGContextDrawImage(bitmap, CGRectMake(-size.width/2, -size.height/2, size.width, size.height), CGImage) 

     let newImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 

     return newImage 
    } 
} 

回答

相關問題