gpt4 book ai didi

ios - 使用 PanGestureRecognizer 裁剪 UIImageView 内 UIImage 的右侧

转载 作者:行者123 更新时间:2023-11-30 14:16:27 24 4
gpt4 key购买 nike

我正在尝试“裁剪”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的配置

感谢您的任何提示。

最佳答案

我按照以下方式解决了它。

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

关于ios - 使用 PanGestureRecognizer 裁剪 UIImageView 内 UIImage 的右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31116867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com