I have seen that in photoshop text can be easily resized just by dragging them. How can we do the same thing in Java? Any idea on how to resize text in java? Added a snapshot of letter "A" resized in photoshop
Please let me know what is wrong with this code?
public class ResizeImage extends JFrame {
public ResizeImage(){
JPanel panel = new JPanel(){
public void paintComponent(Graphics g) {
// In your paint(Graphics g) method
// Create a buffered image for use as text layer
BufferedImage textLayer = new BufferedImage(240, 240,
BufferedImage.TYPE_INT_RGB);
// Get the graphics instance of the buffered image
Graphics2D gBuffImg = textLayer.createGraphics();
// Draw the string
gBuffImg.drawString("Hello World", 10, 10);
// Rescale the string the way you want it
gBuffImg.scale(200, 50);
// Draw the buffered image on the output's graphics object
g.drawImage(textLayer, 0, 0, null);
gBuffImg.dispose();
}
};
add(panel);
}
public static void main(String [] args){
ResizeImage frame = new ResizeImage();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
Unfortunately the java api doesn't have a native free-form scaling/transform method fonts.
You can however rescale a BufferedImage or Graphics object with the
scale(x, y)
method. So you can try an approach with "layers" instead. I.e. draw objects, such as text, in their own layer (i.e. a BufferedImage) first and then on the actual graphics output.So draw the text as usual on a BufferedImage and rescale it the way you want. Here is some simple sample code to get you starting.
The actual size of the text layer could be determined with the help of the FontMetrics object but I'll leave that as an exercise for the OP.
You can use
TextLayout
to get the geometry, as shown here. The example scales the image to fill the frame.JInternalFrame
might be a good choice to leverage the frame's resizing feature. Alternative, the example cited here shows how to click and drag multiple selections.One way is to use an
AffineTransform
(this variant also fades the color).This can be done at the Graphics level using
Graphics.setTransform()
. However I believe it is more obvious to do this at the Font level using the lesser knownFont.deriveFont(transform)
. For exampleu can define type of font
e.g.