Created
August 10, 2014 08:04
-
-
Save yoshimin/142e359443c8c14eec3a to your computer and use it in GitHub Desktop.
UIViewのサブクラスでCoreTextを使い文字を描画
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
| #import "YMNCoreTextView.h" | |
| #import <CoreText/CoreText.h> | |
| #import <QuartzCore/QuartzCore.h> | |
| @interface YMNCoreTextView() | |
| @property (nonatomic, strong) NSMutableAttributedString *attributedString; | |
| @end | |
| @implementation YMNCoreTextView | |
| - (id)initWithText:(NSString*)text item:(NSArray*)items { | |
| self = [super init]; | |
| if (self) { | |
| [self setText]; | |
| } | |
| return self; | |
| } | |
| - (void)setText { | |
| NSString *text = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; | |
| CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"HiraKakuProN-W3", 12.0f, nil); | |
| NSDictionary *attrDictionary = @{(NSString *)kCTFontAttributeName:(__bridge id)fontRef}; | |
| CFRelease(fontRef); | |
| self.attributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:attrDictionary]; | |
| } | |
| - (void)drawRect:(CGRect)rect { | |
| [super drawRect:rect]; | |
| CGContextRef context = UIGraphicsGetCurrentContext(); | |
| // iPhone の座標系と Core Graphics の座標系は、左下が原点なためそのまま描画をすると反転してしまう | |
| // CGContextSetTextMatrix で反転させ CGContextTranslateCTM で並行移動 | |
| CGContextSetTextMatrix(context, CGAffineTransformIdentity); | |
| CGContextTranslateCTM(context, 0.f, rect.size.height); | |
| CGContextScaleCTM(context, 1.f, -1.f); | |
| // 描画範囲を設定して描画 | |
| CGMutablePathRef path = CGPathCreateMutable(); | |
| CGPathAddRect(path, NULL, CGRectMake(0.f, 0.f, rect.size.width, rect.size.height)); | |
| CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)self.attributedString); | |
| CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0.f, self.attributedString.length), path, nil); | |
| CTFrameDraw(frame, context); | |
| CFRelease(frame); | |
| CFRelease(framesetter); | |
| CFRelease(path); | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment