代码之家  ›  专栏  ›  技术社区  ›  Matt S.

按比例获取nstextfield内容

  •  8
  • Matt S.  · 技术社区  · 16 年前

    我怎样才能让文本比例适应我给它的边界呢?

    1 回复  |  直到 16 年前
        1
  •  21
  •   regulus6633    16 年前

    我以前做过类似的事情。

    -(void)calcFontSizeToFitRect:(NSRect)r {
        float targetWidth = r.size.width - xMargin;
        float targetHeight = r.size.height - yMargin;
    
        // the strategy is to start with a small font size and go larger until I'm larger than one of the target sizes
        int i;
        for (i=minFontSize; i<maxFontSize; i++) {
            NSDictionary* attrs = [[NSDictionary alloc] initWithObjectsAndKeys:[NSFont fontWithName:currentFontName size:i], NSFontAttributeName, nil];
            NSSize strSize = [string sizeWithAttributes:attrs];
            [attrs release];
            if (strSize.width > targetWidth || strSize.height > targetHeight) break;
        }
        [self setCurrentFontSize:(i-1)];
    }
    

    字符串变量是要调整大小的文本。xmargin和ymargin变量用于您想要的间距。minfontsize和maxfontsize变量限制了您希望达到的大小。