While playing around with the Java font class and Swing, I set the font size to a negative value.
I discovered that this makes the text be drawn upside down. Is this a bug or a feature? Can anyone explain why this behavior happens?
Try it out:
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class UpsideDown extends JFrame{
public UpsideDown(){
setSize(500,500);
setContentPane(new Panel());
setVisible(true);
}
public class Panel extends JPanel{
public void paintComponent(Graphics g){
Font f = new Font("Sans-Serif", Font.PLAIN, -50);
g.setFont(f);
g.drawString("Upside Down", 400, 100);
}
}
public static void main(String args[]){
new UpsideDown();
}
}
Seems like this is happening:
-50 * glyph_height
is negative -> drawing downwards instead of upwards.In Swing there are very few, if any, absolute quantities. Virtually all quantities are algebraic, meaning that they can be negative, and they can participate in algebraic calculations which may change their sign, as the case is when you multiply by -1. For example, a rectangle can have a negative width, and that's perfectly fine. A font is not an exception to this rule.
Graphics2D
graphics context. (That would be a component that overrides paintComponent( Graphics g )
and begins with Graphics2D g2 = (Graphics2D)g;
) For example, you might have a component that draws a graph, like so:Before the drawing operations, insert the following two lines:
g2.scale( -1.0, -1.0 );
g2.translate( -getWidth(), -getHeight() );
Now check the result. It will all be perfectly up-side down, like this:
Needless to say, if you double the x scale without doubling the y scale, everything will be elongated, including the characters of the text, like so:
This demonstrates how everything, all the way down to the individual coordinates of character glyphs, is an algebraic quantity in Swing.
This gives a great degree of freedom. If you want to invert the graph but keep the text upright, one way to achieve it is to make the font size negative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With