使用 PanGestureRecognizer 在 UIImageView 中裁剪 UIImage 的右侧

Crop right side of UIImage inside UIImageView with a PanGestureRecognizer

我正在尝试 "crop" imageView 中的图像。裁剪的意义:如果用户向左平移,图片将从右侧裁剪到左侧。因此,当用户向右平移时,图片将完全显示,如果用户向左平移,则图片不可见。

我尝试了以下方法:

@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的配置

感谢任何提示。

我按照下面的方法解决了。

我将解释 post 下面的代码。首先,我调整了图像大小以适合 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)
}