当手指在图片中上下滑动的时候,图片的上半部分会有折叠效果。类似地可以扩展到其他需要折叠的场景中。
layer.contentsRect
用来截取layer的部分内容重新在frame中渲染。
代码及关键注释如下:
@interface ViewController ()
{
/**
* 创建两个UIImageView,分别用来保存图片的上、下两部分。
*/
UIImageView *imageViewUp;
UIImageView *imageViewDown;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// Do any additional setup after loading the view, typically from a nib.
imageViewUp = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1"]];
//设置折叠的锚点
imageViewUp.layer.anchorPoint = CGPointMake(0.5, 1);
imageViewUp.frame = CGRectMake(10, 100, 300, 150);
//设置imageView的内容为图片的上半部分
imageViewUp.layer.contentsRect = CGRectMake(0, 0, 1, 0.5);
[self.view addSubview:imageViewUp];
imageViewDown = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1"]];
imageViewDown.layer.anchorPoint = CGPointMake(0.5, 0);
imageViewDown.frame = CGRectMake(10, 250, 300, 150);
imageViewDown.layer.contentsRect = CGRectMake(0, 0.5, 1, 0.5);
[self.view addSubview:imageViewDown];
//添加一个透明浮层,用来捕捉手指滑动。
UIView *clearView = [[UIView alloc] initWithFrame:CGRectMake(10, 100, 300, 300)];
clearView.backgroundColor = [UIColor clearColor];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[clearView addGestureRecognizer:pan];
clearView.userInteractionEnabled = YES;
clearView.tag = 100;
[self.view addSubview:clearView];
}
- (void)pan:(UIPanGestureRecognizer *)ges
{
if (ges.state == UIGestureRecognizerStateChanged) {
UIView *clearView = (UIView *)[imageViewUp viewWithTag:100];
CGPoint point = [ges translationInView:clearView];
//计算旋转角度,拉动距离568时旋转90度。
float R = -point.y*M_PI_2/568.0f;
CATransform3D tran = CATransform3DIdentity;
//设置折叠视角,使之更有立体感
tran.m34 = -1.0/500.0;
imageViewUp.layer.transform = CATransform3DRotate(tran, R, 1, 0, 0);
}
else if(ges.state == UIGestureRecognizerStateEnded)
{
//当松开手指时,图片状态恢复。
[UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{
imageViewUp.layer.transform = CATransform3DIdentity;
} completion:^(BOOL finished) {
nil;
}];
}
}