NSString sizeWithAttributes:内容rect

时间:2010-01-02 21:39:17

标签: cocoa xcode macos nsstring

如何获得NSString的大小,就像它在NSRect中绘制一样。问题是当我尝试 - [NSString sizeWithAttributes:]时,它返回一个NSSize,好像它有无限宽度。我想给方法一个最大宽度。有没有办法这样做? (顺便说一句:Mac OS,而不是iPhone OS)

谢谢, 亚历

4 个答案:

答案 0 :(得分:18)

float heightForStringDrawing(NSString *myString, NSFont *myFont,
        float myWidth)
{
 NSTextStorage *textStorage = [[[NSTextStorage alloc] initWithString:myString] autorelease];
 NSTextContainer *textContainer = [[[NSTextContainer alloc] initWithContainerSize:NSMakeSize(myWidth, FLT_MAX)] autorelease];
 ;
        NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init] autorelease];
 [layoutManager addTextContainer:textContainer];
 [textStorage addLayoutManager:layoutManager];
 [textStorage addAttribute:NSFontAttributeName value:myFont
      range:NSMakeRange(0, [textStorage length])];
 [textContainer setLineFragmentPadding:0.0];

 (void) [layoutManager glyphRangeForTextContainer:textContainer];
 return [layoutManager
   usedRectForTextContainer:textContainer].size.height;
}

毕竟这是在文档中。无论如何,谢谢Joshua!

答案 1 :(得分:6)

我在启用ARC的情况下为iOS修改了Alexandre Cassagne's answer

CGSize ACMStringSize(NSString *string, UIFont *font, CGSize size)
{
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:string];
    [textStorage addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [textStorage length])];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:size];
    textContainer.lineFragmentPadding = 0;
    [layoutManager addTextContainer:textContainer];
    [textStorage addLayoutManager:layoutManager];
    return [layoutManager usedRectForTextContainer:textContainer].size;
}

答案 2 :(得分:1)

我相信你唯一的选择是NSLayoutManager并要求为给定的字形范围使用rects的联合。

答案 3 :(得分:1)

对于OSX可可/迅捷4: (使用自定义NSview来显示如何绘制)

//
//  CustomView.swift
//  DrawMyString
//
//  Created by ing.conti on 19/10/2018.
//  Copyright © 2018 com.ingconti. All rights reserved.
//

import Cocoa

class CustomView: NSView {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        let s : NSString = "AA BB CC DD EE FF"
        let W = 50
        let size = NSSize(width: W, height: 100)

        let boundingRectWithSize  = s.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [:])

        let r = NSRect(origin: CGPoint(x: 20, y: 30), size: boundingRectWithSize.size)

        s.draw(in: r, withAttributes: [:])
        r.frame()
    }
}

(我们还绘制了边框,以查看边框)