forked from sprang/Inkpad
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWDCoreTextLabel.m
More file actions
101 lines (77 loc) · 2.57 KB
/
WDCoreTextLabel.m
File metadata and controls
101 lines (77 loc) · 2.57 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//
// WDCoreTextLabel.m
// Inkpad
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2011-2013 Steve Sprang
//
#import "WDCoreTextLabel.h"
@implementation WDCoreTextLabel
@synthesize fontRef;
@synthesize text;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (!self) {
return nil;
}
self.backgroundColor = nil;
self.opaque = NO;
self.contentMode = UIViewContentModeRedraw;
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
return self;
}
- (void) dealloc
{
if (fontRef) {
CFRelease(fontRef);
}
}
- (void) setFontRef:(CTFontRef)font
{
if (font) {
CFRetain(font);
}
if (fontRef) {
CFRelease(fontRef);
}
fontRef = font;
[self setNeedsDisplay];
}
- (void) setText:(NSString *)inText
{
text = inText;
[self setNeedsDisplay];
}
- (CFMutableAttributedStringRef) newAttributedStringForText:(NSString *)string
{
CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString(attrString, CFRangeMake(0, 0), (CFStringRef)string);
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, CFStringGetLength((CFStringRef)string)), kCTFontAttributeName, [self fontRef]);
return attrString;
}
- (void) drawRect:(CGRect)rect
{
if (!text || [text isEqualToString:@""]) {
return;
}
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1,-1));
CFMutableAttributedStringRef attrString = [self newAttributedStringForText:text];
CFMutableAttributedStringRef tokenString = [self newAttributedStringForText:@"…"];
CTLineRef lineRef = CTLineCreateWithAttributedString(attrString);
CTLineRef tokenLineRef = CTLineCreateWithAttributedString(tokenString);
CTLineRef truncatedLineRef = CTLineCreateTruncatedLine(lineRef, self.bounds.size.width, kCTLineTruncationEnd, tokenLineRef);
float offset = roundf((CGRectGetHeight(self.bounds) - CTFontGetSize(self.fontRef)) / 2) + 2;
CGContextSetTextPosition(ctx, 0, roundf(CGRectGetMaxY(self.bounds) - offset));
CTLineDraw(truncatedLineRef, ctx);
CFRelease(attrString);
CFRelease(tokenString);
CFRelease(lineRef);
CFRelease(tokenLineRef);
CFRelease(truncatedLineRef);
}
@end