2015-06-29 68 views
0

我想「裁剪」imageView中的圖像。裁剪的意義在於:如果用戶向左平移,則圖片會從右側裁剪到左側。所以,當用戶向右移動時,如果用戶向左端移動,則圖片將完全顯示,圖片不可見。使用PanGestureRecognizer在UIImageView中裁剪UIImage的右側

我試過如下:

@IBAction func handlePanGesture(recognizer: UIPanGestureRecognizer) { 
    let translation = recognizer.translationInView(containerView) 

    // Resize the image View 
    let image = imageView.image! 
    let hasAlpha = false 
    let scale: CGFloat = 0.0 

    let newRect = CGRectMake(0, 0, image.size.width - translation.x, image.size.height) 
    UIGraphicsBeginImageContextWithOptions(newRect.size, !hasAlpha, scale) 
    image.drawAtPoint(CGPointMake(-newRect.origin.x, -newRect.origin.y)) 
    let croppedImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

    imageView.image = croppedImage 

    recognizer.setTranslation(CGPointZero, inView: containerView) 
} 

這類作品。查看gif here(目前這隻適用於左圖)。

有人能指出我正確的方向嗎?爲什麼圖像高度不一致,是因爲contentMode設置爲「Aspect Fit」?爲什麼只有在平移到左側時纔會調整大小? Here is a screenshot的配置imageView

感謝您的任何提示。

+0

無論你想甚至可以改變圖像視圖的高度與平移手勢一起??? –

+0

只要寬度應該改變。高度可以保持不變。 – heikomania

+0

即將生病發送給我你正在處理的代碼 –

回答

0

我解決了它以下面的方式。

我會解釋併發佈下面的代碼。首先,我調整圖像以適應imageView。這樣我可以將contentMode設置爲.Left。其次我保存了兩張圖片。所以,一張照片可以從右向左裁剪,當用戶從左到右平移時,可以顛倒一張照片。 從上面我的裁剪功能將不起作用,所以我用CGImageCreateWithImageInRect(_:_:)裁剪它們。

下面是這對我的作品的UIPanGestureRecognizer代碼:

@IBAction func handlePanGesture(recognizer: UIPanGestureRecognizer) { 
    let translation = recognizer.translationInView(containerView) 
    let imageLeft = googleImageView.image! 
    let imageRef = CGImageCreateCopy(initiallyScaledImage?.CGImage) 
    let imageRight = UIImage(CGImage: imageRef!, scale: (initiallyScaledImage?.scale)!, orientation: (initiallyScaledImage?.imageOrientation)!) 

    if translation.x < 0 { 
     let scale = imageLeft.scale 
     let newRect = CGRectMake(0, 0, (imageLeft.size.width + translation.x) * scale, imageLeft.size.height * scale) 
     let imageRef = CGImageCreateWithImageInRect(imageLeft.CGImage, newRect) 

     if let croppedImage = imageRef { 
      googleImageView.image = UIImage(CGImage: croppedImage, scale: scale, orientation: imageLeft.imageOrientation) 
     } 
    } else if translation.x > 0 { 
     // Get the rect from above, add translation, set new picture 
     let scale = imageRight.scale 
     let newRect = CGRectMake(0, 0, (imageLeft.size.width + translation.x) * scale, imageRight.size.height * scale) 
     let imageRef = CGImageCreateWithImageInRect(imageRight.CGImage, newRect) 

     if let uncroppedImage = imageRef { 
      googleImageView.image = UIImage(CGImage: uncroppedImage, scale: scale, orientation: imageRight.imageOrientation) 
     } 
    } 

    recognizer.setTranslation(CGPointZero, inView: containerView) 
}