場(chǎng)景:當(dāng)UIView正在做動(dòng)畫時(shí),實(shí)時(shí)如何獲取UIView的frame?
對(duì)策:
每個(gè) CALayer 有一個(gè) presentationLayer 屬性草冈,當(dāng)CAAnimation發(fā)生時(shí)猎提,你在屏幕上看到的實(shí)際上是 presentation layer 的改變抠璃。如果你訪問(wèn) presentation layer挤渐,QuartzCore 將會(huì)計(jì)算現(xiàn)有的幀狀態(tài)阵翎,并且使用這個(gè)幀狀態(tài)去構(gòu)建 presentation layer 對(duì)象裆赵。因?yàn)閯?dòng)畫狀態(tài)在動(dòng)畫執(zhí)行期間一直處于改變东囚,因此你將會(huì)獲得近似值。
presentationLayer 和 NSTimer 結(jié)合使用就可以滿足前面需求
下面是demo:
- (void)viewDidLoad {
[superviewDidLoad];
self.imageView= [[UIViewalloc]init];
self.imageView.backgroundColor= [UIColorredColor];
self.imageView.frame=CGRectMake(100,100,100,150);
[self.viewaddSubview:self.imageView];
NSTimer*timer = [NSTimertimerWithTimeInterval:0.1target:selfselector:@selector(currentRect:)userInfo:nilrepeats:YES];
[[NSRunLoopcurrentRunLoop]addTimer:timerforMode:NSDefaultRunLoopMode];
[UIViewanimateWithDuration:5.0animations:^{
self.imageView.center=CGPointMake(200,300);
}];
}
-(void)currentRect:(NSTimer*)timer
{
CGRectimageViewCurrentRect = [[self.imageView.layerpresentationLayer]frame];
NSLog(@"x: %lf, y:%lf",imageViewCurrentRect.origin.x,imageViewCurrentRect.origin.y);
}