label中的文字类似跑马灯的效果

来源:互联网 发布:python statement 编辑:程序博客网 时间:2024/05/10 15:09

label中的文字类似跑马灯的效果

 
转载
一行中的文字实现在固定的区域跑马灯效果!

h文件:

#import <UIKit/UIKit.h>



@interface MyLabel : UIViewController {

UILabel *label;

UILabel *big;

}

@property (nonatomic, retain) UILabel *label;

@property (nonatomic, retain) UILabel *big;


-(id)initWithMyFrame:(CGRect)frame;

-(void)startAnimation:(NSString *)string;

@end


m文件:

 

#import "MyLabel.h"



@implementation MyLabel

@synthesize label,big;


 

-(id)initWithMyFrame:(CGRect)frame

{

self = [super init];

if(self)

{

self.view = [[UIView alloc] initWithFrame:frame];

}

 

label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];

big = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];

[self.view insertSubview:big atIndex:0];

[big setBackgroundColor:[UIColor clearColor]];

[big setTextColor:[UIColor whiteColor]];

 

[self.view setBackgroundColor:[UIColor clearColor]];

 

[self.view setClipsToBounds:YES];//移动到view外面的不显示

 

return self;

}



-(void)startAnimation:(NSString *)string

{

int length = [string length];

 

CGRect labFrame = self.label.frame;

CGSize labSize = labFrame.size;

 

UIFont *font = [UIFont fontWithName:@"Georgia-Bold" size:17];

[big setFont:font];

 


if(length * 17 < labSize.width)

{

[big.layer removeAnimationForKey:@"animateLayer"];

big.frame = CGRectMake(0, 0, length*17, self.label.frame.size.height);

big.text = string;

 

//[CATransaction commit];//如果这里再次提交,就把anmiation给取消掉了,因为frame重设,removeanimation了。

 

}

else 

{

big.text = string;

 

big.frame = CGRectMake(self.label.frame.size.width, 0, length*17, self.label.frame.size.height);

 

 

//[CATransaction commit];//如果在这里提交会覆盖上一个animation的效果

 

 

CABasicAnimation *theAnimation;    

theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];

theAnimation.duration=3;

theAnimation.repeatCount=999999;

theAnimation.autoreverses=NO;

theAnimation.toValue=[NSNumber numberWithFloat:-length*17-self.label.frame.size.width];

[big.layer addAnimation:theAnimation forKey:@"animateLayer"];

 

}

 


}


- (void)dealloc {

[big release];

[label release];

    [super dealloc];

}



@end

 

0 0
原创粉丝点击