2017-03-29 4 views
0

Comment puis-je envelopper le texte en fonction de la taille du texteEnveloppe de texte sur une image à l'aide de graphiques?

g.drawString("Hello, please help me in wrapping the text", 100, 100); 

sortie - texte en ligne droite:

https://i.stack.imgur.com/oUcMd.jpg

sortie nécessaire - texte Enveloppé basé sur la longueur du texte:

https://i.stack.imgur.com/MldhL.jpg

Comment atteindre la sortie requise? gaspillé beaucoup de temps à le comprendre, mais inutile, avec une explication est très appréciée.

+1

Votre après [Dessin plusieurs lignes de texte] (https://docs.oracle.com/javase/tutorial/2d/text/drawmulstring.html) – MadProgrammer

Répondre

2

L'habillage de mots à l'aide de HTML est le moyen le plus simple d'aborder ce problème.

enter image description here

import java.awt.*; 
import java.awt.image.BufferedImage; 
import javax.swing.*; 

public class LabelRenderTest { 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       String title = "<html><body style='" 
         + "text-align: center; width: 100px; padding: 5px;'>" 
         + "<p>Hello, please help me in<br>wrapping the text"; 

       BufferedImage image = new BufferedImage(
         200, 
         100, 
         BufferedImage.TYPE_INT_RGB); 

       JLabel textLabel = new JLabel(title); 
       textLabel.setSize(textLabel.getPreferredSize()); 
       textLabel.setForeground(Color.WHITE); 

       Graphics2D g = image.createGraphics(); 
       textLabel.paint(g); 
       g.dispose(); 

       JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(image))); 
      } 
     }); 
    } 
}