2009-12-15 94 views
1

this previous question類似,我想對任意圖像應用任意顏色的色調(UIImageView)。但是,我希望色彩在N秒鐘內消失,以產生「脈衝」效果。我會每M秒觸發一次脈衝。動畫UIImageView色調

雖然我認爲我可以使用NSTimer來改變顏色,但我認爲我可以使用一些Core Animation框架來創建更加優雅(高效)的解決方案。不過,我對Core Animation不是很熟悉。

正在用Core Animation創建這樣的「脈衝」嗎?如果是這樣,怎麼樣?

回答

1

如果您打算使用Core Animation,該方法將與鏈接到以前的SO問題時演示的方法不同。相反,創建一個圖層,使用您之後的顏色進行着色,然後爲該圖層的不透明度設置動畫效果。事情是這樣的:

CALayer *tintLayer = [CALayer layer]; 

// Center the layer on the view 
[tintLayer setBounds:[imageView bounds]]; 
[tintLayer setPosition:CGPointMake([imageView bounds].size.width/2.0, 
            [imageView bounds].size.height/2.0)]; 

// Fill the color 
[tintLayer setBackgroundColor: 
      [[UIColor colorWithRed:0.5 green:0.5 blue:0.0 alpha:1.0] CGColor]]; 
[tintLayer setOpacity:0.5]; 
[[imageView layer] addSublayer:tintLayer]; 

// Add the animation 
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"]; 
[animation setFromValue:[NSNumber numberWithFloat:0.5]]; 
[animation setToValue:[NSNumber numberWithFloat:0.0]]; 
// Animate back to the starting value automatically 
[animation setAutoreverses:YES]; 
// Animate over the course of 5 seconds. 
[animation setDuration:5.0]; 

[tintLayer addAnimation:animation forKey:@"opacity"]; 

我不知道的是它是否會工作一樣,因爲我們沒有指定在色彩層的混合模式,唯一的問題。我將不得不查看默認情況下使用CA進行的混合。

此致敬禮。

更新:找到another SO後,說在CA混合取決於該層的'不透明'屬性。

+0

如果上述任意圖像不是矩形(如圓圈),或者它周圍有空白邊框(帶有0 alpha的像素),這樣做會工作嗎?因爲如果你打電話給setBackgroundColor :,你會爲那些不應該被「點亮」的像素設置顏色。 – 2009-12-16 18:13:20

+0

好吧,它會着色整個矩形。不過,我認爲這也適用於其他Core Graphics方法。但我不確定,因爲我沒有嘗試過。 – 2009-12-16 18:43:17

+0

你可以添加一個掩碼到tintLayer。我正在着色UIImageView - tintLayer.mask = imageView.layer可能會做到這一點。希望imageView.layer喜歡在兩個地方使用。 – 2013-05-23 06:41:36