Fonte de gráficos Java - Como garantir que os personagens estejam em determinada área?
-
21-09-2019 - |
Pergunta
Eu tenho uma imagem. Na parte inferior da imagem, gostaria de criar uma faixa colorida, digamos, de altura 100. Já terminei a criação da tira e posso basicamente escrever cordas nessa parte (por exemplo, direitos autorais da imagem etc). O seguinte é o meu método.
public static BufferedImage captionMyImage(BufferedImage sourceImage) {
int height=sourceImage.getHeight();
int width=sourceImage.getWidth();
System.out.println("Image Height: "+height);
System.out.println("Image Width: "+width);
int min=20; //fifty pixels
int newHeight=(int) (0.1*height>min ? 1.1*height : height+min);
int difference=newHeight-height;
System.out.println("new height:"+newHeight);
System.out.println("Difference:"+difference);
BufferedImage bgImage=new BufferedImage(width,newHeight,BufferedImage.TYPE_INT_RGB);
/**Create a Graphics from the background image**/
Graphics2D g = bgImage.createGraphics();
//g.drawRect(0, 0, width, ((int)0.1*height>min) ? (int)1.1*height : height+min);
g.setColor(Color.RED);
g.fillRect(0, 0, bgImage.getWidth(), bgImage.getHeight());
g.setColor(Color.YELLOW);
/**Set Antialias Rendering**/
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
/**
* Draw background image at location (0,0)
* You can change the (x,y) value as required
*/
g.drawImage(sourceImage, 0, 0, null);
int strX=sourceImage.getWidth()/2;
int strY=sourceImage.getHeight()+difference/2;
System.out.println("X: "+strX);
System.out.println("Y: "+strY);
g.setFont(new Font(g.getFont().getName(),Font.PLAIN,20));
g.drawString("(c)www.sanjaal.com",strX ,strY);
g.dispose();
return bgImage;
}
Eu sei da maneira como calculei os valores para x e y para o método destring () é apenas simples e tem um problema que o texto sai do limite às vezes (dependendo do tamanho da imagem e comprimento do texto)
Gostaria de garantir que o texto na imagem na tira inferior que eu defini sempre se alinhe à parte direita (limite) da imagem, mas não sai do limite. Como posso conseguir isso? Lembre -se de que o comprimento do texto pode ser dinâmico.
Os especialistas em gráficos da Java compartilhariam suas idéias sobre como isso pode ser alcançado?
Solução
String msg = "(c)www.sanjaal.com";
int margin = 2;
g.drawString(msg, getWidth() - g.getFontMetrics().stringWidth(msg) - margin, strY);