2015-11-07 95 views
0

我有一個UIScrollView其中UIImageView裏面。對於我的應用程序的這部分,用戶可以從他們的相機膠捲中選擇照片並縮放和裁剪它們。ios - 可以裁剪照片垂直但不水平

我已經成功地讓用戶能夠選擇不同的照片,然後放大和縮小圖像周圍的泛光燈&。此外,用戶可以縮小圖像中心,使其垂直或水平取決於圖像是縱向還是橫向。

問題是,我嘗試從滾動視圖中的可見矩形裁剪照片爲新圖像,但是它僅適用於人像照片。

這裏再工作不工作的這一個例子:

這裏是縮小以適應屏幕的肖像圖片:

enter image description here

接下來,我放大圖像沒有黑色空間。

enter image description here

最後,我裁剪的照片,你可以看到它完美作物在左上角。

enter image description here

然而,由於某些原因,當我試圖用景觀圖像裁剪弄亂做到這一點?這是一個不起作用的例子。

這是放大的橫向圖像。

enter image description here

接下來,我放大所以沒有留下黑色的空間。請注意,我是如何放大的,因此照片中沒有白板的實際邊框。

enter image description here

現在,我裁剪的照片像以前一樣,並沒有正確地裁剪。請注意,圖像與左上角的左上角不同。它似乎已經縮小,你可以看到更多的白板底部。

enter image description here

我需要弄清楚爲什麼發生這種情況,以及如何解決它。

下面是我用來從UIScrollView裁剪照片的確切代碼。

//Get the scale 
    float scale = 1.0f/_libraryScrollView.zoomScale; 

    //Create a new rect 
    CGRect visibleRect; 
    visibleRect.origin.x = _libraryScrollView.contentOffset.x * scale; 
    visibleRect.origin.y = _libraryScrollView.contentOffset.y * scale; 
    visibleRect.size.width = _libraryScrollView.bounds.size.width * scale; 
    visibleRect.size.height = _libraryScrollView.bounds.size.height * scale; 

    //Get the source image 
    UIImage *src = libraryPreviewImageView.image; 

    //Create the new cropped image with the rect 
    CGImageRef cr = CGImageCreateWithImageInRect(src.CGImage, visibleRect); 
    UIImage *finalImage = [[UIImage alloc]initWithCGImage:cr]; 

    //Set the new image to the preview image view 
    self.imagePreviewView.image = finalImage; 

此代碼適用於縱向圖像,但不適用於橫向圖像,如上例所示。這個錯誤與我的裁剪代碼有關,還是與其他東西有關?

任何幫助,將不勝感激。

回答

0

最後,我不知道是什麼問題,但試圖使用數學從滾動視圖中裁剪圖像是非常困難的!

我發現了一個非常簡單的方法,那就是採取滾動視圖可見內容的截屏,它的那麼容易,因爲這樣的:

UIGraphicsBeginImageContextWithOptions(_libraryScrollView.bounds.size, YES, [UIScreen mainScreen].scale); 
CGPoint offset = _libraryScrollView.contentOffset; 
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -offset.x, -offset.y); 
[_libraryScrollView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

//Set the new image to the preview image view 
self.imagePreviewView.image = finalImage; 

我真的希望這個答案可以幫助其他人了太!