我想使用手势识别器在居中的图像视图中拖动,并希望在不再拖动时再次重新居中。
1)使用ImageView创建VC
2)将其限制在所有侧面20个(我使用的是Tabbar控制器,因此距离控制器顶部20个像素会更好)
3)将其设置为Aspect Fit
4)为您的VC创建出口
5)在ImageView中添加一个手势识别器
let gesture = UIPanGestureRecognizer(target: self, action: #selector(imageDragged(gestureRecognizer:)))
matchImageView.addGestureRecognizer(gesture)
6)创建imageDragged函数
@objc func imageDragged(gestureRecognizer: UIPanGestureRecognizer){
//Current Point where the label is dragged
let draggedLabelPoint = gestureRecognizer.translation(in: view)
//Updating the center of the label : viewcenter +/- currentpoint
matchImageView.center = CGPoint(x: view.bounds.width/2 + draggedLabelPoint.x, y: view.bounds.height/2 + draggedLabelPoint.y)
let xFromCenter = view.bounds.width/2 - matchImageView.center.x
var rotation = CGAffineTransform(rotationAngle: xFromCenter / -500)
let scale = min(100/abs(xFromCenter),1)
var scaledAndRotated = rotation.scaledBy(x: scale, y: scale)
//Transforming the Item respective to the distance from center
matchImageView.transform = scaledAndRotated
if gestureRecognizer.state == .ended {
//If Image is out of bounds -> left
if matchImageView.center.x < (view.bounds.width/2 - 120) {
matchImageView.alpha = 0
}
//If Image is out of bounds -> right
if matchImageView.center.x > (view.bounds.width/2 + 120) {
matchImageView.alpha = 0
}
//Reset the scaling variables and recentering the Item after swipe
rotation = CGAffineTransform(rotationAngle: 0)
scaledAndRotated = rotation.scaledBy(x: 1, y: 1)
matchImageView.transform = scaledAndRotated
matchImageView.center = CGPoint(x: view.bounds.width/2, y: view.bounds.height/2)
7)使用不同的长宽比图像测试此功能
当我点击图像并将其拖动一点以使手势识别器能够识别出运动时,图像视图会捕捉到几个像素。我认为这种捕捉的强度还取决于源图像的长宽比。
图像应始终位于可用视图的中心,并且无论宽高比如何,中心点之间都不应存在差异。
我试图创建一个偏移量变量以使其平滑,但仅凭肉眼就不可能缩小该大小。