專著:http://www.lxweimin.com/p/a490131e00e7
效果如下:
001.gif
思路
創(chuàng)建一個view 作為所有內容的父控件, 并且添加到上面一個 label, 作為顯示文字的載體
UILabel* contentLabel = [[UILabelalloc] init];[contentLabel sizeToFit];contentLabel.backgroundColor= [UIColorclearColor]; _contentLabel = contentLabel; [selfaddSubview:self.contentLabel];
給內容view的layer添加一個mask層, 并且設置其范圍為整個view的bounds, 這樣就讓超出view的內容不會顯示出來
CAShapeLayer* maskLayer = [CAShapeLayerlayer];maskLayer.path= [UIBezierPathbezierPathWithRect:self.bounds].CGPath;self.layer.mask= maskLayer;
給label添加動畫
CAKeyframeAnimation* keyFrame = [CAKeyframeAnimationanimation];keyFrame.keyPath=@"transform.translation.x";keyFrame.values= @[@(0), @(-space), @(0)];keyFrame.repeatCount=NSIntegerMax;keyFrame.duration=self.speed*self.contentLabel.text.length;keyFrame.timingFunctions= @[[CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseInEaseOut], [CAMediaTimingFunctionfunctionWithControlPoints:0:0:0.5:0.5]];keyFrame.delegate=self;[self.contentLabel.layeraddAnimation:keyFrame forKey:nil];
使用方法
// 創(chuàng)建CFDynamicLabel* testLabel = [[CFDynamicLabelalloc] initWithFrame:CGRectMake(100,300,180,21)];// 設置滾動速度testLabel.speed=0.6;[self.viewaddSubview:testLabel];// 設置基本屬性testLabel.text=@"我不想說再見,不說再見,越長大越孤單";testLabel.textColor= [UIColoryellowColor];testLabel.font= [UIFontsystemFontOfSize:23];testLabel.backgroundColor= [UIColorgrayColor];