2012-11-27 80 views
4

我有一個Canvas,其中包含一個Label。我想根據畫布大小設置此標籤的字體大小。 我們如何做到這一點?如何計算標籤的最大適配字體大小?

編輯:「包含」的意思是,畫布和標籤邊界是相同的。編輯2:我有這個爲Swing,但我不能將其轉換爲SWT;但我不能將它轉換爲SWT;我不能將它轉換爲SWT;我不能將它轉換爲SWT;我不能將它轉換爲SWT;

Font labelFont = label.getFont(); 
String labelText = label.getText(); 
int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText); 
int componentWidth = label.getWidth(); 
double widthRatio = (double)componentWidth/(double)stringWidth; 
int newFontSize = (int)(labelFont.getSize() * widthRatio); 
int componentHeight = label.getHeight(); 
int fontSizeToUse = Math.min(newFontSize, componentHeight); 

EDIT3: 這是標籤

public class FitFontSize { 
    public static int Calculate(Label l) { 
     Point size = l.getSize(); 
     FontData[] fontData = l.getFont().getFontData(); 
     GC gc = new GC(l); 

     int stringWidth = gc.stringExtent(l.getText()).x; 

     double widthRatio = (double) size.x/(double) stringWidth; 
     int newFontSize = (int) (fontData[0].getHeight() * widthRatio); 

     int componentHeight = size.y; 
     System.out.println(newFontSize + " " + componentHeight); 
     return Math.min(newFontSize, componentHeight); 
    } 
} 

我的字體大小計算器類,這是我在窗口頂部的標籤。我想根據圖層大小的體積來設置它的字體大小。

Label l = new Label(shell, SWT.NONE); 
    l.setText("TITLE HERE"); 
    l.setBounds(0,0,shell.getClientArea().width, (shell.getClientArea().height * 10)/ 100); 
    l.setFont(new Font(display, "Tahoma", 16,SWT.BOLD)); 
    l.setFont(new Font(display, "Tahoma", FitFontSize.Calculate(l),SWT.BOLD)); 

回答

9

我剛剛移植了上面的代碼。

你可以得到一個String在SWT的程度(長度)與方法GC.stringExtent();而且需要具備類FontData可以獲得字體高度和Label的字體寬度。

Label label = new Label(parent, SWT.BORDER); 
    label.setSize(50, 30); 
    label.setText("String"); 

    // Get the label size and the font data 
    Point size = label.getSize(); 
    FontData[] fontData = label.getFont().getFontData(); 
    GC gc = new GC(label); 

    int stringWidth = gc.stringExtent(label.getText()).x; 

    // Note: In original answer was ...size.x + (double)..., must be/not + 
    double widthRatio = (double) size.x/(double) stringWidth; 
    int newFontSize = (int) (fontData[0].getHeight() * widthRatio); 

    int componentHeight = size.y; 
    int fontsizeToUse = Math.min(newFontSize, componentHeight); 

    // set the font 
    fontData[0].setHeight(fontsizeToUse); 
    label.setFont(new Font(Display.getCurrent(), fontData[0])); 

    gc.dispose(); 

來源:

+1

@延娜:爲了記錄在案,你的示例代碼不處置'GC'實例(我知道OP沒有,但這就是我們爲什麼要糾正它)。 任何人複製/粘貼你的代碼會因此引入一個微妙的UI漏洞,在資源被泄露的地方,因爲我不得不在其他人的代碼中查找這樣的錯誤,我可以說它可以導致UI更新凍結,小部件被繪製在其他窗戶或其他古怪的部分。 – JBert