需要缩放字体以适应矩形的方式 [英] Need a way to scale a font to fit a rectangle

查看:146
本文介绍了需要缩放字体以适应矩形的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是写了一些代码来缩放字体以适应矩形的长度。它开始于18宽度和迭代,直到它适合。

这似乎是非常低效率,但我找不到一个循环的方式来做到这一点。
这行代码用于缩放游戏网格中的标签,所以我看不到解决方法(包装,剪切和延伸到矩形之外都是不可接受的)。



这其实很快,我为数百个矩形做了这个,速度足够快,只是减缓了一下触摸。 b $ b

如果没有人提出任何更好的建议,我只是从表格中加载开始的猜测(所以它比18更接近),并使用它 - 除了它的延迟效果很好。

  public font scaleFont(String text,Rectangle rect,Graphics g,Font pFont){
float nextTry = 18.0f;
Font font = pFont;

while(x> 4){
font = g.getFont()。deriveFont(nextTry);
FontMetrics fm = g.getFontMetrics(font);
int width = fm.stringWidth(text);
if(width< = rect.width)
返回字体;
nextTry * =。9;
}
返回字体;

$ / code $ / $ p

解决方案

半伪代码: / p>

  public font scaleFont(String text,Rectangle rect,Graphics g,Font pFont){
float fontSize = 20.0f;
Font font = pFont;

font = g.getFont()。deriveFont(fontSize);
int width = g.getFontMetrics(font).stringWidth(text);
fontSize =(rect.width / width)* fontSize;
返回g.getFont()。deriveFont(fontSize);



$ b $ p
$ b

我不知道为什么你通过pFont,因为它不使用.. 。


I just wrote some code to scale a font to fit within (the length of) a rectangle. It starts at 18 width and iterates down until it fits.

This seems horribly inefficient, but I can't find a non-looping way to do it. This line is for labels in a game grid that scales, so I can't see a work-around solution (wrapping, cutting off and extending past the rectangle are all unacceptable).

It's actually pretty quick, I'm doing this for hundreds of rectangles and it's fast enough to just slow it down a touch.

If nobody comes up with anything better, I'll just load the starting guess from a table (so that it's much closer than 18) and use this--except for the lag it works great.

public Font scaleFont(String text, Rectangle rect, Graphics g, Font pFont) {
    float nextTry=18.0f;
    Font font=pFont;

    while(x > 4) {                             
            font=g.getFont().deriveFont(nextTry);
            FontMetrics fm=g.getFontMetrics(font);
            int width=fm.stringWidth(text);
            if(width <= rect.width)
                return font;
            nextTry*=.9;            
    }
    return font;
}

解决方案

semi-psuedo code:

public Font scaleFont(String text, Rectangle rect, Graphics g, Font pFont) {
    float fontSize = 20.0f;
    Font font = pFont;

    font = g.getFont().deriveFont(fontSize);
    int width = g.getFontMetrics(font).stringWidth(text);
    fontSize = (rect.width / width ) * fontSize;
    return g.getFont().deriveFont(fontSize);
}

i'm not sure why you pass in pFont as it's not used...

这篇关于需要缩放字体以适应矩形的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆