模拟tvOS中的3D浮动效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
-(void)setUpSomething{

self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowOffset = CGSizeMake(0, 10);
self.layer.shadowRadius = 10.0f;
self.layer.shadowOpacity = 0.3f;

cardImageView = [[UIImageView alloc]initWithFrame:self.bounds];
cardImageView.image = [UIImage imageNamed:@"Group 24"];
cardImageView.layer.cornerRadius = 5.0f;
cardImageView.clipsToBounds = YES;
[self addSubview:cardImageView];

UIPanGestureRecognizer *panGes = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panInCard:)];

[self addGestureRecognizer:panGes];

cardParallaxView = [[UIImageView alloc]initWithFrame:cardImageView.frame];
cardParallaxView.image = [UIImage imageNamed:@"Group 25"];
cardParallaxView.layer.transform = CATransform3DTranslate(cardParallaxView.layer.transform, 0, 0, 200);
[self insertSubview:cardParallaxView aboveSubview:cardImageView];

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
-(void)panInCard:(UIPanGestureRecognizer *)panGes{

CGPoint touchPoint = [panGes locationInView:self];

if (panGes.state == UIGestureRecognizerStateChanged) {

CGFloat xFactor = MIN(1, MAX(-1,(touchPoint.x - (self.bounds.size.width/2)) / (self.bounds.size.width/2)));
CGFloat yFactor = MIN(1, MAX(-1,(touchPoint.y - (self.bounds.size.height/2)) / (self.bounds.size.height/2)));

cardImageView.layer.transform = [self transformWithM34:1.0/-500 xf:xFactor yf:yFactor];
cardParallaxView.layer.transform = [self transformWithM34:1.0/-250 xf:xFactor yf:yFactor];


}else if (panGes.state == UIGestureRecognizerStateEnded){

[UIView animateWithDuration:0.3 animations:^{
cardImageView.layer.transform = CATransform3DIdentity;
cardParallaxView.layer.transform = CATransform3DIdentity;
} completion:NULL];

}

}
1
2
3
4
5
6
7
8
9
-(CATransform3D )transformWithM34:(CGFloat)m34 xf:(CGFloat)xf yf:(CGFloat)yf{

CATransform3D t = CATransform3DIdentity;
t.m34 = m34;
t = CATransform3DRotate(t, M_PI/9 * xf, 0, 1, 0);
t = CATransform3DRotate(t, M_PI/9 * yf, -1, 0, 0);
return t;

}