..once my text is converted to image then how do I edit it (eg: changing the text color, etc).
Don't. It is better (quality) and easier to paint the image each choice with the text when requested, in the desired Font
, starting Point
, AffineTransform
, RenderinhHints
and Color
(etc.).
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
public class StretchLabels {
String s = "The quick brown fox jumps over the lazy dog!";
Font font = new Font(Font.SERIF, Font.PLAIN, 24);
public JComponent getGUI() {
JPanel gui = new JPanel(new BorderLayout());
JLabel l1 = new StretchTextLabel(s);
l1.setFont(font);
gui.add(l1, BorderLayout.CENTER);
return gui;
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("Streeetch me!");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
StretchLabels eg = new StretchLabels();
f.setContentPane(eg.getGUI());
f.pack();
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
class StretchTextLabel extends JLabel {
private static final long serialVersionUID = 1L;
public StretchTextLabel(String s) {
super(s);
}
@Override
public void paintComponent(Graphics gr) {
Color c = gr.getColor();
setForeground(new Color(0,0,0,0));
super.paintComponent(gr);
setForeground(c);
gr.setColor(c);
Graphics2D g = (Graphics2D)gr;
g.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
double pw = this.getPreferredSize().width;
double ph = this.getPreferredSize().height;
double w = this.getSize().width;
double h = this.getSize().height;
// Set FG (text) color
g.setColor(this.getForeground());
// stretch
AffineTransform stretch =
AffineTransform.getScaleInstance(w/pw, h/ph);
g.setTransform(stretch);
g.drawString(getText(), 0, this.getFont().getSize());
}
}
.. how do I edit the text in the image?
I typically offer controls to do it like this:
But of course, that does not cover:
- Color, which has a control in the main GUI (a basic paint app.)
- Scaling of the resulting text by 'drag'. Which might be achieved by using a resizable element as demonstrated by either @trashgod or myself (above).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…