[英]How to inherit animation properties while animating CALayer with implicit animation
我試圖使用隱式動畫在CALayer上設置自定義屬性的動畫:
[UIView animateWithDuration:2.0f animations:^{
self.imageView.myLayer.myProperty = 1;
}];
在-actionForKey:方法我需要返回動畫,負責插值。 當然,我必須以某種方式告訴動畫如何檢索動畫的其他參數(即持續時間和計時功能 )。
- (id<CAAction>)actionForKey:(NSString *)event
{
if ([event isEqualToString:@"myProperty"])
{
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"myProperty"];
[anim setFromValue:@(self.myProperty)];
[anim setKeyPath:@"myProperty"];
return anim;
}
return [super actionForKey:event];
}
}
有關如何實現這一點的任何想法? 我嘗試在圖層屬性中查找動畫,但找不到任何有趣的內容。 我也有動畫層動畫的問題,因為actionForKey:在動畫之外被調用。
我估計你有一個自定義屬性,你自定義屬性“myProperty”,你添加到UIView的支持層 - 根據文檔UIView動畫塊不支持自定義圖層屬性的動畫,並聲明需要使用CoreAnimation:
更改視圖擁有的圖層與更改視圖本身相同,並且應用於圖層屬性的任何動畫都會遵循當前基於視圖的動畫塊的動畫參數。 對於您自己創建的圖層,情況也是如此。 自定義圖層對象忽略基於視圖的動畫塊參數,而是使用默認的Core Animation參數。
如果要為您創建的圖層自定義動畫參數,則必須直接使用Core Animation。
此外,文檔聲稱UIView僅支持一組有限的可動畫屬性:
視圖支持一組涵蓋許多常見任務的基本動畫。 例如,您可以對視圖屬性進行動畫處理或使用過渡動畫將一組視圖替換為另一組視圖。
表4-1列出了可動畫的屬性 - 具有內置動畫支持的屬性 - UIView類。
你必須為此創建一個CABasicAnimation。
如果在actionForKey中返回CABasicAnimation,則可以使用CATransactions進行某種解決方法:就像那樣
[UIView animateWithDuration:duration animations:^{
[CATransaction begin];
[CATransaction setAnimationDuration:duration];
customLayer.myProperty = 1000; //whatever your property takes
[CATransaction commit];
}];
只需將actionForKey:方法更改為類似的方法即可
- (id<CAAction>)actionForKey:(NSString *)event
{
if ([event isEqualToString:@"myProperty"])
{
return [CABasicAnimation animationWithKeyPath:event];
}
return [super actionForKey:event];
}
如果你不想看看Github有什么東西: https : //github.com/iMartinKiss/UIView-AnimatedProperty
如果您使用以下內容,我認為您無法訪問該持續時間 :
[UIView animateWithDuration:duration animations:^{
}];
您的代碼的其他問題是,如果在動畫塊中調用代碼,則UIView的actionForKey:UIView的實現僅返回CAAnimation對象。 否則返回null以關閉動畫。 在您的實現中,您始終返回CAAnimation,因此將始終對更改為該屬性進行動畫處理。
你應該用這個:
[CATransaction begin];
[CATransaction setAnimationDuration:duration];
[CATransaction setAnimationTimingFunction:timingFunction];
customLayer.myProperty = 1000; //whatever your property takes
[CATransaction commit];
然后在actionForKey:方法中,使用[CATransaction animationDuration]
和[CATransaction animationTimingFunction]
來檢索當前持續時間和計時功能。
最簡單的方法可能是在 myProperty 之前設置的自定義圖層中的另一個屬性。 喜歡:
self.imageView.myLayer.myTimingFunction = kCAMediaTimingFunctionEaseInEaseOut;
self.imageView.myLayer.myProperty = 1;
和
-(id<CAAction>)actionForKey:(NSString *)event
{
if ([event isEqualToString:@"myProperty"])
{
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"myProperty"];
[anim setFromValue:@(self.myProperty)];
[anim setKeyPath:@"myProperty"];
[anim setTimingFunction:myTimingFunction];
return anim;
}
return [super actionForKey:event];
}
}
如果你想獲得參數,比如持續時間 ,請設置
[UIView animateWithDuration:2.0f ...
所以在這種情況下持續時間= 2.0f
你可以使用CATransaction和valueForKey 。 CATransaction應返回上下文的特定值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.