Skip to content

Instantly share code, notes, and snippets.

@dimitribouniol
Created January 24, 2011 16:47
Show Gist options
  • Save dimitribouniol/793504 to your computer and use it in GitHub Desktop.
Save dimitribouniol/793504 to your computer and use it in GitHub Desktop.
UIKit-based string additions for those who are going "Back to the Mac™"
#import <Cocoa/Cocoa.h>
@interface NSString (DBMoreStringAdditions)
- (CGSize)sizeWithFont:(NSFont *)aFont;
- (void)drawAtPoint:(CGPoint)point withFont:(NSFont *)aFont;
- (void)drawAtPoint:(CGPoint)point withFont:(NSFont *)aFont color:(NSColor *)aColor;
- (CGSize)sizeWithFont:(NSFont *)aFont actualFontSize:(CGFloat *)fontSize forWidth:(CGFloat)width;
- (CGSize)sizeWithFont:(NSFont *)aFont constrainedToSize:(CGSize)aSize;
@end
#import "NSString+DBMoreStringAdditions.h"
@implementation NSString (DMMoreStringAdditions)
- (CGSize)sizeWithFont:(NSFont *)aFont
{
NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys:aFont, NSFontAttributeName, nil];
NSSize size = [self sizeWithAttributes:attributes];
[attributes release];
return CGSizeMake(size.width, size.height);
}
- (void)drawAtPoint:(CGPoint)point withFont:(NSFont *)aFont
{
NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys:aFont, NSFontAttributeName, nil];
[self drawAtPoint:NSMakePoint(point.x, point.y) withAttributes:attributes];
[attributes release];
}
- (void)drawAtPoint:(CGPoint)point withFont:(NSFont *)aFont color:(NSColor *)aColor
{
NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys:aFont, NSFontAttributeName, aColor, NSForegroundColorAttributeName, nil];
[self drawAtPoint:NSMakePoint(point.x, point.y) withAttributes:attributes];
[attributes release];
}
- (CGSize)sizeWithFont:(NSFont *)aFont actualFontSize:(CGFloat *)fontSize forWidth:(CGFloat)width
{
CGSize returnSize = [self sizeWithFont:aFont];
*fontSize = [aFont pointSize];
if (returnSize.width < width) {
*fontSize = width * (*fontSize) / returnSize.width;
returnSize.height = width * returnSize.height/returnSize.width;
returnSize.width = width;
}
return returnSize;
}
- (CGSize)sizeWithFont:(NSFont *)aFont constrainedToSize:(CGSize)aSize
{
NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys:aFont, NSFontAttributeName, nil];
NSRect boundingRect = [self boundingRectWithSize:aSize options:NULL attributes:attributes];
[attributes release];
return CGSizeMake(boundingRect.size.width, boundingRect.size.height);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment