我正在尝试在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'?为什么只有在向左平移时才调整大小? {4}} imageView的配置
感谢您的任何提示。
答案 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)
}