Created
September 27, 2010 05:25
-
-
Save arunthampi/598652 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSMutableAttributedString *)attributedStringFromMarkup:(NSString *)markup { | |
NSMutableAttributedString * mutableAttrString = [[[NSMutableAttributedString alloc] initWithString:@""] autorelease]; | |
NSString * nextTextChunk = nil; | |
NSString * defaultFont = @"Georgia"; | |
NSString * boldFont = @"Georgia-Bold"; | |
NSString * headingFont = @"Gill-Sans"; | |
CGFloat defaultFontSize = 18.0; | |
CGFloat headingFontSize = 22.0; | |
CGFloat fontSize = 0.0; | |
NSString * fontFace = nil; | |
NSScanner * markupScanner = [NSScanner scannerWithString:markup]; | |
[markupScanner setCharactersToBeSkipped:nil]; | |
while (![markupScanner isAtEnd]) { | |
[markupScanner scanUpToString:@"<" intoString:&nextTextChunk]; | |
[markupScanner scanString:@"<" intoString:NULL]; | |
if ([nextTextChunk length] > 0) { | |
CTFontRef currentFont = CTFontCreateWithName((CFStringRef)(fontFace ? fontFace : defaultFont), | |
(fontSize != 0.0 ? fontSize : defaultFontSize), NULL); | |
UIColor * color = [UIColor blackColor]; | |
NSDictionary * attrs = [NSDictionary dictionaryWithObjectsAndKeys: | |
(id)color.CGColor, kCTForegroundColorAttributeName, | |
(id)currentFont, kCTFontAttributeName, | |
nil]; | |
NSAttributedString * newPiece = [[[NSAttributedString alloc] initWithString:nextTextChunk attributes:attrs] autorelease]; | |
[mutableAttrString appendAttributedString:newPiece]; | |
CFRelease(currentFont); | |
nextTextChunk = nil; | |
} | |
NSString * elementData = nil; | |
[markupScanner scanUpToString:@">" intoString:&elementData]; | |
[markupScanner scanString:@">" intoString:NULL]; | |
if (elementData) { | |
if ([elementData length] == 1) { | |
// Opening Tag | |
if ([elementData caseInsensitiveCompare:@"b"] == NSOrderedSame) { | |
fontFace = boldFont; | |
fontSize = defaultFontSize; | |
} else if ([elementData caseInsensitiveCompare:@"h"] == NSOrderedSame) { | |
fontFace = headingFont; | |
fontSize = headingFontSize; | |
} else { | |
fontFace = nil; | |
fontSize = 0.0; | |
} | |
} else { | |
// Closing Tag | |
fontSize = 0.0; | |
fontFace = nil; | |
} | |
} | |
} | |
return mutableAttrString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment