- (CGSize)sizeWithFont:(UIFont *)font
Tags: iPhone, Objective-C, UIKit
[iPhone] HTMLリンクのようなUIButtonのサブクラスでボタンタイトルの文字列の長さに応じてアンダーラインを引く方法を試行錯誤していたが、NSStringオブジェクトのCGSizeを返すメソッドであっさり解決した。
// UIStringDrawing.h // UIKit @interface NSString(UIStringDrawing) - (CGSize)sizeWithFont:(UIFont *)font; @end
修正前
// HTMLLinkButton.m - (void)drawRect:(CGRect)rect { CGFloat w = rect.size.width; CGFloat h = rect.size.height; CGFloat capHeight = self.font.capHeight; CGFloat xHeight = self.font.xHeight; CGFloat underlineLength = [_buttonTitle length] * xHeight; CGFloat startX = (w - underlineLength) / 2.0; CGFloat startY = (h + capHeight) / 2.0; CGFloat endX = startX + underlineLength; CGFloat endY = startY; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, _colorController.currentColor.CGColor); CGContextMoveToPoint(context, startX, startY); CGContextAddLineToPoint(context, endX, endY); CGContextStrokePath(context); }
修正後
// HTMLLinkButton.m - (void)drawRect:(CGRect)rect { CGFloat w = rect.size.width; CGFloat h = rect.size.height; CGFloat titleWidth = [_buttonTitle sizeWithFont:self.font].width; CGFloat titleHeight = [_buttonTitle sizeWithFont:self.font].height; CGFloat descender = self.font.descender; CGFloat startX = (w - titleWidth) / 2.0; CGFloat startY = (h + titleHeight) / 2.0 + descender; CGFloat endX = startX + titleWidth; CGFloat endY = startY; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, _colorController.currentColor.CGColor); CGContextMoveToPoint(context, startX, startY); CGContextAddLineToPoint(context, endX, endY); CGContextStrokePath(context); }
Related posts:
Title Link
Trackback URL
Comments
One Response to “- (CGSize)sizeWithFont:(UIFont *)font”
Leave a Reply



[…] (**追記2009/05/02: 文字列の長さ・高さの扱いは- (CGSize)sizeWithFont:(UIFont *)fontでスマートに解決した) […]