2015-05-12 79 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 
    } 
} 

回答

相关问题