Highlighted text in iOS (karaoke like app)

后端 未结 2 1266
无人共我
无人共我 2020-12-29 13:51

I am trying to create a karaoke-like application but I\'m facing a problem.

I have a song as an mp3 and the corresponding lyrics shown in a UITextView. I want to hig

相关标签:
2条回答
  • 2020-12-29 14:09

    I found that the easiest way to do this would be using a uiwebview, insert the text in html format and underline/highlight it using javascript...hope it helps to everyone who want to do this :)

    0 讨论(0)
  • 2020-12-29 14:16

    As I see it you have two options:

    1. Core Text Attributes

    With Core Text, you can underline words and apply many other ornaments to them. Here's an example for underlining text:

    //Create a font
    CTFontRef sysUIFont = CTFontCreateUIFontForLanguage(kCTFontSystemFontType,
        24.0, NULL);
    
    //Create a string
    NSString *aString = @"Random text";
    
    //Choose the color
    CGColorRef color = [UIColor blueColor].CGColor;
    
    //Single underline
    NSNumber *underline = [NSNumber numberWithInt:kCTUnderlineStyleSingle];
    
    //Pack the attributes into a dictionary
    NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
        (id)sysUIFont, (id)kCTFontAttributeName,
        color, (id)kCTForegroundColorAttributeName,
        underline, (id)kCTUnderlineStyleAttributeName, nil];
    
    //Make the attributed string
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:string
        attributes:attributesDict];
    

    Now this works fine for underlining text, but I'm not sure how to animate the underline moving from word to word as the lyrics progress.


    2. Custom UIView Underline

    Now your second option is to create a custom underline class that subclasses UIView. This would be easy to animate. You don't even have to create a separate class for the underline (though I recommend it); you could just create a UIView and animate it moving from word to word with an animation like the following:

    CABasicAnimation *underlineMove = [CABasicAnimation animationWithKeyPath:@"position"];
    underlineMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    endPosition = CGPointMake((float)nextWord.x, (float)nextWord.y);
    underlineMove.toValue = [NSValue valueWithCGPoint:endPosition];
    underlineMove.duration = currentWord.duration;
    [underlineView addAnimation:underlineMove forKey:@"animation"];
    
    0 讨论(0)
提交回复
热议问题