2017-05-05 45 views
0

工作,我想顯示在揮杆對象(JLabel的,等等),表情符號,所以爲了做到這一點我使用this library及以下類,使表情符號,顯示只是Graphics2D的drawString之不帶顏色的字體

jLabel.setIcon(new EmojiIcon(":poop:")); 

與具有除了那些表情符號支援這些彩色的所有字體(即EmojiOneNoto Color Emoji

什麼是單色的表情符號點工作?

public class EmojiIcon implements Icon { 
    private Font font; 
    private final static int DEFAULT_SIZE = 32; 
    private int    width  = DEFAULT_SIZE; 
    private int    height  = DEFAULT_SIZE; 

    private String emoji; 

    public EmojiIcon (String iconString){ 
     this.emoji = EmojiParser.parseToUnicode(iconString); 
     setFont("emojione-android"); 
     recalculateIconWidth(emoji); 
    } 

    public void setFont(String strFont){ 
     try { 
      font = Font.createFont(Font.TRUETYPE_FONT, new File("fonts/"+strFont+".ttf")).deriveFont(48f); 
     } catch (FontFormatException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    private void recalculateIconWidth(String iconString){ 
     FontRenderContext frc = new FontRenderContext(null, true, true); 
     Rectangle2D bounds = font.getStringBounds(iconString, frc); 
     width = (int) bounds.getWidth(); 
     height = (int) bounds.getHeight(); 
    } 

    @Override 
    public void paintIcon(Component c, Graphics g, int x, int y){ 
     Graphics2D g2d = (Graphics2D) g; 

     g2d.setFont(font); 
     g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); 
     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 

     g2d.drawString(emoji, 0, height); 
    } 
} 

我一直在尋找在線羯羊是它甚至合法的字體有顏色的,所以我發現here它不會standarised(至少.TTF字體)。 有沒有解決這個問題的方法?我真的很喜歡使用EmojiOne font

回答

0

這部分負荷字體:

  GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
     ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, Thread.currentThread().getContextClassLoader().getResourceAsStream("path/milibus-rg.ttf"))); 

此繪製文字:

public static BufferedImage textToImage(String text, Font font, int bottomPadding, Color color, BufferedImage background) { 
    int width = background.getGraphics().getFontMetrics(font).stringWidth(text); 
    int height = background.getGraphics().getFontMetrics(font).getHeight(); 
    BufferedImage bufferedImage = new BufferedImage(width, height, TYPE_4BYTE_ABGR); 
    Graphics2D graphics = bufferedImage.createGraphics(); 
    graphics.setBackground(new Color(0f, 0f, 0f, .0f)); //transparent 
    graphics.setColor(color); 
    graphics.setFont(font); 
    graphics.drawString(text, 0, height - bottomPadding); 
    graphics.dispose(); 
    return bufferedImage; 
}