整个效果有两个视图:蓝色View和红色View,可以把红色View的效果拆分为水平方向的平移和整个的缩放,这样水平方向可以获取实时的x坐标改变,缩放的话,可以使用transform来实现。
第一步就是实现红色View水平方向的平移效果,只需要计算出,上一次的X值和当前X值的差值,就能计算出本次X方向平移的距离:
1、添加平移手势
2、获取手势平移的坐标点
3、根据左边点的X值进行平移
做好水平方向的平移后,就可以实现View的缩放了:
1、先确定一个缩放的目标比例
红色View到最右边,缩放到70%,就可以根据红色View的X和目标值,得出一个实时的缩放比例;
2、利用transform来进行缩放
#import "FLDragerVC.h"
#define FLScreenW [UIScreen mainScreen].bounds.size.width
#define FLTarget FLScreenW * 0.8
@interface FLDragerVC ()
/** leftView*/
@property (weak, nonatomic) UIView *leftV;
/** mainView*/
@property (weak, nonatomic) UIView *mainV;
@end
@implementation FLDragerVC
- (void)viewDidLoad {
[super viewDidLoad];
[self addChildView];
UIPanGestureRecognizer *panG = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
[self.mainV addGestureRecognizer:panG];
}
- (void)panGesture:(UIPanGestureRecognizer *)panG {
NSLog(@"%s", __func__);
// 相对最原始的点,每次清零后,变成了一次平移走的距离
CGPoint mainVP = [panG translationInView:self.mainV];
NSLog(@"%@",NSStringFromCGPoint(mainVP));
[self positionTranslateScal:mainVP.x];
if (panG.state == UIGestureRecognizerStateEnded) {
// 手势结束时,是否超过的屏幕的一半
if (self.mainV.frame.origin.x > FLScreenW *0.5) {
[self openDrager];
} else {
[self closeDrager];
}
}
// 清0操作
[panG setTranslation:CGPointZero inView:self.mainV];
}
- (void)openDrager{
[UIView animateWithDuration:0.25 animations:^{
[self positionTranslateScal:FLTarget];
CGRect frame = self.mainV.frame;
frame.origin.x = FLTarget;
self.mainV.frame = frame;
}];
}
- (void)closeDrager {
[UIView animateWithDuration:0.25 animations:^{
self.mainV.frame = [UIScreen mainScreen].bounds;
// 清空Transform形变
self.mainV.transform = CGAffineTransformIdentity;
}];
}
/**
根据mainV平移手势的位置,来决定mainV的平移和缩放
*/
- (void)positionTranslateScal:(CGFloat)value {
CGRect frame = self.mainV.frame;
// 每次x都增加一个增量
frame.origin.x += value;
self.mainV.frame = frame;
// 让mainV不能向左移动
if (self.mainV.frame.origin.x < 0) {
self.mainV.frame = [UIScreen mainScreen].bounds;
}
// mainV的X值超过目标x值,不再让mainV向右移动
if (self.mainV.frame.origin.x > FLTarget) {
CGRect frame = self.mainV.frame;
frame.origin.x = FLTarget;
self.mainV.frame = frame;
}
// 当mainV向右滑动至最右边时,缩放至70%,即缩放0.3
CGFloat scale = 0.3 * self.mainV.frame.origin.x / FLScreenW;
// 当前的缩放比例
CGFloat currScale = 1- scale;
self.mainV.transform = CGAffineTransformMakeScale(currScale, currScale);
}
- (void)addChildView {
UIView *leftV = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
leftV.backgroundColor = [UIColor blueColor];
self.leftV = leftV;
[self.view addSubview:leftV];
UIView *mainV = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
mainV.backgroundColor = [UIColor redColor];
self.mainV = mainV;
[self.view addSubview:mainV];
}
@end
注意:每次平移都要平移手势的point做清0操作,关闭抽屉效果时,一定要清空所有的transform效果
网友评论