用平移动画效果实现电梯门的开或关的效果
我公司刚刚启动一个IOS项目,该项目和电梯相关,其中就涉及到电梯门的开和关。
1. 准备素材
美工准备了4张png图片, 1张电梯的环境图,1张电梯的背景图(电梯门在打开时电梯里的背景),1张左门,1张右门。
因为环境图的中间是电梯背景部分,所以电梯门所在位置的矩形区域必须为透明的。
2. 创建对象
在MyViewController.h中定义2个对象:
UIImageView* largeBk; // 环境图的对象
LiftView* liftView; // 电梯视图, LiftView从UIView继承,封装了2个电梯门对象,负责开门和关门
3. 调整层次关系
largeBk 位于 liftView的上层,不用担心liftView被遮挡,因为环境图的电梯区域是透明的。
4. 参考LiftView的源代码
1 @implementation LiftView 2 @synthesize opened; 3 4 - (id)initWithFrameAndState:(CGRect)frame state:(BOOL)stateOpened 5 { 6 self = [super initWithFrame:frame]; 7 if (self) { 8 bk = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size 9 .width, self.frame.size.height)]; 10 bk.image = [UIImage imageNamed:@"lift_inside@2x.png"]; // 电梯背景 11 [self addSubview:bk]; 12 if (stateOpened) 13 [self createDoorsWithOpened]; 14 else 15 [self createDoorsWithClosed]; 16 [self addSubview:leftDoor]; 17 [self addSubview:rightDoor]; 18 }19 20 return self; 21 }
// 默认初始状态门是开的 22 - (void)createDoorsWithOpened 23 { 24 CGRect leftFrame = CGRectMake(0 - self.frame.size.width/2,0,self.frame.size.width/2,self.frame.size.height); 25 leftDoor = [[UIImageView alloc]initWithFrame:leftFrame]; 26 27 CGRect rightFrame = CGRectMake(0 + self.frame.size.width, 0, self.frame.size.width/2, self.frame.size.height); 28 rightDoor = [[UIImageView alloc]initWithFrame:rightFrame]; 29 30 leftDoor.image = [UIImage imageNamed:@"liftgate_left.png"]; 31 rightDoor.image = [UIImage imageNamed:@"liftgate_right.png"]; 32 opened = YES; 33 } 34 // 默认初始状态是关的 35 - (void)createDoorsWithClosed 36 { 37 CGRect leftFrame = CGRectMake(0,0,self.frame.size.width/2,self.frame.size.height); 38 leftDoor = [[UIImageView alloc]initWithFrame:leftFrame]; 39 40 CGRect rightFrame = CGRectMake(0 + self.frame.size.width/2, 0, self.frame.size.width/2, self.frame.size.height); 41 rightDoor = [[UIImageView alloc]initWithFrame:rightFrame]; 42 43 leftDoor.image = [UIImage imageNamed:@"liftgate_left.png"]; 44 rightDoor.image = [UIImage imageNamed:@"liftgate_right.png"]; 45 opened = NO; 46 } 47 48 - (void)openDoor 49 { 50 if( self.opened ){ 51 NSLog(@"openDoor warning: door has been opened!"); 52 return; 53 } 54 float oneDoorWidth = leftDoor.frame.size.width; 55 56 [UIView beginAnimations:nil context:nil]; 57 [UIView setAnimationDuration:1]; // 动画周期为1秒 58 leftDoor.transform = CGAffineTransformMakeTranslation(-1*oneDoorWidth, 0); 59 rightDoor.transform = CGAffineTransformMakeTranslation(+1*oneDoorWidth, 0); 60 [UIView commitAnimations]; 61 self.opened = YES; 62 } 63 - (void)closeDoor 64 { 65 if( !self.opened ){ 66 NSLog(@"closeDoor warning: door has been closed!"); 67 return; 68 } 69 //float oneDoorWidth = leftDoor.frame.size.width; 70 // 关门时,还原变换即可 71 [UIView beginAnimations:nil context:nil]; 72 [UIView setAnimationDuration:1]; 73 leftDoor.transform = CGAffineTransformMakeTranslation(0, 0); 74 rightDoor.transform = CGAffineTransformMakeTranslation(0, 0); 75 [UIView commitAnimations]; 76 77 self.opened = NO; 78 } 79 80 81 @end