2016-06-21 78 views
0

我在drawRect中繪製了一個指南針撥號盤,我想避免重繪它,但是將它轉換爲標題指南針標題更改。當我使用CABasicAnimation這樣的:旋轉不帶動畫的自定義UIView

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; 
animation.fromValue = [NSNumber numberWithFloat:_dialAngle*M_PI/180]; 
animation.toValue = [NSNumber numberWithFloat:dialAngle*M_PI/180]; 
animation.duration = 0.0; 
animation.repeatCount = 0; 
animation.removedOnCompletion = false; 
animation.fillMode = kCAFillModeForwards; 
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; 
[dial.layer addAnimation:animation forKey:@"transform.rotation.z"]; 

它旋轉如預期(頂部和文字紅色箭頭是從指南針刻度盤不同的看法):

enter image description here

我真的不希望動畫,所以我用的變體,如:

[dial.layer setValue:[NSNumber numberWithDouble: dialAngle*M_PI/180] forKeyPath:@"transform.rotation.z"]; 

或者:

dial.transform = CGAffineTransformMakeRotation(arrowAngle*M_PI/180); 

或者:

CATransform3D t = CATransform3DIdentity; 

dial.layer.transform = CATransform3DRotate(t, dialAngle*M_PI/180, 0.0, 0.0, 1.0); 

他們都得出了相同的結果歪斜:

enter image description here

自動佈局和約束不存在於這個觀點。

我應該錯過了一些東西,我不知道它是什麼。我錯過了什麼以獲得與動畫相同的結果?

此外,從您的經驗,我應該真的使用旋轉轉換有利於drawRect?在profiler中,我看到drawRect需要花費很多CPU週期。當我使用轉換時,我沒有看到「我的」cpu週期,但是當我密集旋轉時,總CPU值幾乎相同。

這將是偉大的馴服轉換你的幫助:)!

回答

0

將我的頭靠在牆上並查看視圖上的.transform值後,我發現問題出在layoutSubviews中設置視圖的框架中。當僅使用邊界和中心時:

dial.bounds = self.bounds; 
dial.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); 

它正確地與問題中提到的所有轉換選項一起工作。

原來,這是一個衆所周知的事實,即如果在視圖上設置了非標識轉換(docs),則不應觸摸框架。

但是,如果transform屬性包含非標識轉換,那麼frame屬性的值是未定義的,不應該修改。在這種情況下,您可以使用center屬性重新定位視圖,並使用bounds屬性調整大小。

另外,請確保不要在其他地方使用變換視圖的.frame。我在drawRect中將它用作.frame.size,當然必須將其更改爲.bounds.size。