Created
February 13, 2014 08:31
-
-
Save datafatmunger/8971699 to your computer and use it in GitHub Desktop.
iOS7 boundingRectWithSize Example
This file contains 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
// | |
// TSTView.m | |
// Test | |
// | |
// Created by James Bryan Graves on 09-02-14. | |
// Copyright (c) 2014 Qardio. All rights reserved. | |
// | |
#import "TSTView.h" | |
@implementation TSTView | |
- (id)initWithFrame:(CGRect)frame | |
{ | |
self = [super initWithFrame:frame]; | |
if (self) { | |
self.backgroundColor = [UIColor redColor]; | |
} | |
return self; | |
} | |
// Only override drawRect: if you perform custom drawing. | |
// An empty implementation adversely affects performance during animation. | |
- (void)drawRect:(CGRect)rect { | |
UIFont *font = [UIFont boldSystemFontOfSize:24]; | |
NSMutableParagraphStyle *style = [NSMutableParagraphStyle new]; | |
style.alignment = NSTextAlignmentCenter; | |
style.lineBreakMode = NSLineBreakByWordWrapping; | |
NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"Say something meaningful here?" attributes:@{NSFontAttributeName:font, NSParagraphStyleAttributeName: style}]; | |
CGSize strSize = [str boundingRectWithSize:CGSizeMake(self.frame.size.width, self.frame.size.height) | |
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | |
context:nil].size; | |
NSLog(@"RECT: %@", NSStringFromCGSize(strSize)); | |
CGRect frame = CGRectMake((rect.size.width/2) - (strSize.width/2), | |
(rect.size.height/2) - (strSize.height/2), | |
strSize.width, | |
strSize.height); | |
CGContextRef context = UIGraphicsGetCurrentContext(); | |
CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 1.0); | |
CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0); | |
CGContextFillRect(context, frame); | |
CGContextStrokeRect(context, frame); | |
[str drawWithRect:frame options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment