Created
April 2, 2017 16:34
-
-
Save MrPowerGamerBR/818632d87c6f413f72a3de9fe37e60b4 to your computer and use it in GitHub Desktop.
Write text in images (and wrap it if needed)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mrpowergamerbr.loritta.utils; | |
import java.awt.FontMetrics; | |
import java.awt.Graphics; | |
public class ImageUtils { | |
/** | |
* Escreve um texto em um Graphics, fazendo wrap caso necessário | |
* @param text Texto | |
* @param startX X inicial | |
* @param startY Y inicial | |
* @param endX X máximo, caso o texto ultrapasse o endX, ele automaticamente irá fazer wrap para a próxima linha | |
* @param endY Y máximo, atualmente unused | |
* @param fontMetrics Metrics da fonte | |
* @param graphics Graphics usado para escrever a imagem | |
* @return Y final | |
*/ | |
public static int drawTextWrap(String text, int startX, int startY, int endX, int endY, FontMetrics fontMetrics, Graphics graphics) { | |
int lineHeight = fontMetrics.getHeight(); // Aqui é a altura da nossa fonte | |
int currentX = startX; // X atual | |
int currentY = startY; // Y atual | |
for (char c : text.toCharArray()) { | |
int width = fontMetrics.charWidth(c); // Width do char (normalmente é 16) | |
if ((currentX + width) > endX) { // Se o currentX é maior que o endX... (Nós usamos currentX + width para verificar "ahead of time") | |
currentX = startX; // Nós iremos fazer wrapping do texto | |
currentY = currentY + lineHeight; | |
} | |
graphics.drawString(String.valueOf(c), currentX, currentY); // Escreva o char na imagem | |
currentX = currentX + width; // E adicione o width no nosso currentX | |
} | |
return currentY; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment