Is it possible in Java (using the awt library) to draw diagonal lines, and other shapes, with smooth lines? That is, without visible pixel squares. The image shows that the diagonal lines go like a ladder, but it is necessary that they be "smooth". That is, is it possible to draw exactly (smooth, vector) lines in Java and, if possible, how to do it?
|
1 answer
In this case, you need to inherit from the Component class and override the paint (Graphics g) method as follows:
public void paint(Graphics g) { //ΡΠ³Π»Π°ΠΆΠΈΠ²Π°Π½ΠΈΠ΅: Π΄Π΅Π»Π°Π΅Ρ Π³ΡΠ°ΡΠΈΠΊΡ Π² Swing Π±ΠΎΠ»Π΅Π΅ ΠΊΡΠ°ΡΠΈΠ²ΠΎΠΉ Graphics2D g2 = (Graphics2D) g; //ΠΏΡΠ΅ΠΎΠ±ΡΠ°Π·ΡΠ΅ΠΌ Graphics Π² Graphics2D g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); //ΡΠ³Π»Π°ΠΆΠΈΠ²Π°Π½ΠΈΠ΅ g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON); }
This will make Swing graphics more attractive, without ladders and pixel squares.
Just do not forget to "attach" the class that draws the components to the frame itself.
Suppose you can do this in the constructor:
public class FrameCreator extends Component{ JFrame frame; //ΠΊΠΎΠ΄... public FrameCreator(){ frame = new JFrame(); //ΠΊΠΎΠ΄... frame.add(this); //ΠΏΠΎΠ·Π²ΠΎΠ»ΡΠ΅Ρ ΠΏΡΠΈΠΊΡΠ΅ΠΏΠΈΡΡ Π½Π° ΡΡΠ΅ΠΉΠΌ ΠΊΠ»Π°ΡΡ, ΠΊΠΎΡΠΎΡΡΠΉ ΡΠΈΡΡΠ΅Ρ ΡΠ»Π΅ΠΌΠ΅Π½ΡΡ } }
- This method has already been tried, but with it smoothing is not perfect. "Ladder" is still visible. The only difference is that the boundaries of the steps have become duller. - Nikolai
- oneWell, it seems to me that for Swing this is already the limit. The library was written a long time ago, and if you want something more powerful, then use javaFX (this library is already loaded in IntelijIdea). - SlandShow
|