本段代码转自一个示例代码.
播放器文字高光效果:
-(void)settext:(NSString *)te
{
if (text!=nil)
{
[text release];
text = nil;
}
text = [te retain];
CGSize size1 = [text sizeWithFont:FONT];
NSLog(@"%f %f",size1.width,size1.height);
CGSize size = [text sizeWithFont:FONT constrainedToSize:self.frame.size
lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"%f %f",size.width,size.height);
linenum = size.height/size1.height;
hight = size.height;
len = 0;
if ([t isValid])
{
[t invalidate];
[t release];
}
t = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:0.01 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
[self setNeedsDisplay];
}
-(void)timerFired:(NSTimer*)timer
{
NSLog(@"timer运行");
//[t invalidate];
//[t release];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
int linew = rect.size.width;
int linehighe = hight/linenum;
int line = len/linew;
int linex = len%linew;
NSLog(@"行数:%d 烈数:%d",line,linex);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
if (line>0)
{
CGContextSetRGBFillColor(context, 1, 1, 1, 1);
CGContextFillRect(context, CGRectMake(0.0,0.0,linew,line*linehighe));
}
if (linex>0)
{
CGContextSetRGBFillColor(context, 1, 1, 1, 1);
CGContextFillRect(context, CGRectMake(0.0,line*linehighe,linex,linehighe));
}
CGContextSetRGBFillColor(context, 0.5, 0.1, 0.8, 1);
CGContextFillRect(context, CGRectMake(linex,line*linehighe,linew - linex,linehighe));
CGContextFillRect(context, CGRectMake(0.0,(line+1)*linehighe,linew,(linenum-1-line)*linehighe));
CGImageRef alphaMask = CGBitmapContextCreateImage(context);
CGContextRestoreGState(context);
/*
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetRGBFillColor(context, 0.5, 0.1, 0.8, 1);
CGContextFillRect(context, CGRectMake(0.0, 0.0, rect.size.width/2,rect.size.height));
CGContextSetRGBFillColor(context, 1, 1, 1, 1);
CGContextFillRect(context, CGRectMake(rect.size.width/2, 0, rect.size.width/2,rect.size.height));
CGImageRef alphaMask = CGBitmapContextCreateImage(context);
CGContextRestoreGState(context);
*/
CGContextSetRGBFillColor(context, 0.5, 0.5, 0.5, 1);
CGContextFillRect(context, rect);
CGContextClipToMask(context, rect, alphaMask);
[[UIColor greenColor] setFill];
[text drawInRect:rect withFont:FONT];
CGImageRelease(alphaMask);
CGContextRestoreGState(context);
len++;
}