1首先定義 前端
@interface ViewController ()
{
CAGradientLayer* _gridentlayer;
}
@end 數組
2 在viewDidLoad中實現 ide
//這裏出現了CALayer的另外一個子類CAGradientLayer,這個類的做用就是能在Layer上繪製出漸變顏色的效果,而後在viewDidLoad()中添加以下代碼:
_gridentlayer = [[CAGradientLayer alloc] init];
_gridentlayer.bounds=CGRectMake(0, 0,self.backgroundView.frame.size.width, self.backgroundView.frame.size.height);
_gridentlayer.position=CGPointMake(self.backgroundView.frame.size.width/2, self.backgroundView.frame.size.height/2);
// gradientLayer.colors = [
//UIColor.blackColor().CGColor,
// UIColor.whiteColor().CGColor,
// UIColor.blackColor().CGColor
// ]
//上述兩行的代碼是設置Layer的大小及位置
[_gridentlayer setStartPoint:CGPointMake(0, 0.5)];
[_gridentlayer setEndPoint:CGPointMake(1, 0.5)];
/**
CAGradientLayer的colors屬性類型是一個數組[AnyObject],這就意味着咱們能夠實現多個顏色的漸變效果,而且能夠規定各個顏色的順序。不過在咱們這個示例中咱們只須要兩種顏色,不過須要注意的是雖然顏色只有兩種,可是整個顏色漸變的過程當中有三個原色點,那就是黑、白、黑,因此咱們在這個數組中也須要按照原色點的數量和順序添加相應的顏色,哪怕顏色都是同樣的。
咱們既然設置了漸變的三個原色,那麼就要對這原色出現的位置進行設置,接着添加以下代碼:
*/
[_gridentlayer setColors:[NSArray arrayWithObjects:(id)[UIColor blackColor].CGColor,(id)[UIColor whiteColor].CGColor,(id)[UIColor blackColor].CGColor, nil]];
[_gridentlayer setLocations:@[@0.2 ,@0.5,@0.8]];
[self.backgroundView.layer addSublayer:_gridentlayer]; 動畫
} .net
-(void)viewDidAppear:(BOOL)animated{
[self gradinetAnimate];
}
-(void)gradinetAnimate{
// self.textlabel.text=@"caoxiang";
// _gridentlayer.mask=self.textlabel.layer;
// 首先,建立了一個locations類型的動畫實例gradient,將fromValue屬性,也就是起始位置的屬性設置爲[0, 0, 0.25],它的意思是動畫開始前,黑色、白色這兩個原色的位置在整個Layer的最前端,第二個黑色原色在0.25的位置:
CABasicAnimation * animation=[CABasicAnimation animationWithKeyPath:@"locations"];
[animation setFromValue:@[@0,@0,@0.25]];
[animation setToValue:@[@0.75,@1,@1]];
//而結束位置toValue,將白色和第二個黑色原色位置設置在整個Layer的末端,第一個黑色原色在0.75的位置:
// 從圖中能夠看出,此時整個Layer都變成了黑色。也就是說,在整個動畫中,第一個黑色原色從0移動到0.75的位置,白色原色從0移動到1的位置,第二個黑色原色從0.25移動到1的位置。而後設置動畫時間爲2秒,無線重複次數,最後將gradient動畫添加到gradientLayer中。咱們在viewDidAppear()方法中調用該動畫方法gradientAnimate(),編譯運行看看效果:
animation.duration=2;
animation.repeatCount=HUGE;
[_gridentlayer addAnimation:animation forKey:nil];
self.textlabel.text=@"hahahahaha";
_gridentlayer.mask=self.textlabel.layer;
} get
效果圖:
animation