-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
NSAttributedString+SmallCaps.m
86 lines (66 loc) · 2.35 KB
/
NSAttributedString+SmallCaps.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// NSAttributedString+SmallCaps.m
// DTCoreText
//
// Created by Oliver Drobnik on 31.01.12.
// Copyright (c) 2012 Drobnik.com. All rights reserved.
//
#import "NSAttributedString+SmallCaps.h"
#import "DTCoreText.h"
@implementation NSAttributedString (SmallCaps)
+ (NSAttributedString *)synthesizedSmallCapsAttributedStringWithText:(NSString *)text attributes:(NSDictionary *)attributes
{
id normalFont = [attributes objectForKey:(id)kCTFontAttributeName];
DTCoreTextFontDescriptor *smallerFontDesc = nil;
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_5_1
if ([normalFont isKindOfClass:[UIFont class]])
{
// UIKit Font
UIFont *font = normalFont;
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
smallerFontDesc = [DTCoreTextFontDescriptor fontDescriptorForCTFont:ctFont];
CFRelease(ctFont);
}
else
#endif
{
// CTFontRef
smallerFontDesc = [DTCoreTextFontDescriptor fontDescriptorForCTFont:(__bridge CTFontRef)normalFont];
}
smallerFontDesc.pointSize *= 0.7;
CTFontRef smallerFont = [smallerFontDesc newMatchingFont];
NSMutableDictionary *smallAttributes = [attributes mutableCopy];
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_5_1
if (___useiOS6Attributes)
{
UIFont *uiFont = [UIFont fontWithCTFont:smallerFont];
[smallAttributes setObject:uiFont forKey:NSFontAttributeName];
CFRelease(smallerFont);
}
else
#endif
{
[smallAttributes setObject:CFBridgingRelease(smallerFont) forKey:(id)kCTFontAttributeName];
}
NSMutableAttributedString *tmpString = [[NSMutableAttributedString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:text];
[scanner setCharactersToBeSkipped:nil];
NSCharacterSet *lowerCaseChars = [NSCharacterSet lowercaseLetterCharacterSet];
while (![scanner isAtEnd])
{
NSString *part;
if ([scanner scanCharactersFromSet:lowerCaseChars intoString:&part])
{
part = [part uppercaseString];
NSAttributedString *partString = [[NSAttributedString alloc] initWithString:part attributes:smallAttributes];
[tmpString appendAttributedString:partString];
}
if ([scanner scanUpToCharactersFromSet:lowerCaseChars intoString:&part])
{
NSAttributedString *partString = [[NSAttributedString alloc] initWithString:part attributes:attributes];
[tmpString appendAttributedString:partString];
}
}
return tmpString;
}
@end