How in Java to make a figure translucent? Are there any built-in methods for this? For example, draw a circle and fill it with red. Then on top of it I draw a rectangle, larger in size and fill it with, let's say, blue. It is necessary to set a certain level of translucency for the rectangle in order to see the circle under it. Is it possible to do this?

    1 answer 1

    You can either set the color of the transparency, or, for more complex cases, use AlphaComposite

     public class Alpha { static void initUi() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE ); JPanel colorWithAlpha = new JPanel() { @Override public void paintComponent( Graphics g ) { g.setColor( Color.WHITE ); g.fillRect( 0, 0, getWidth(), getHeight() ); g.setColor( Color.RED ); g.fillOval( 0, 0, getWidth(), getHeight() ); // rgba, a - Π°Π»ΡŒΡ„Π°-ΠΊΠ°Π½Π°Π», Π½Π΅ΠΏΡ€ΠΎΠ·Ρ€Π°Ρ‡Π½ΠΎΡΡ‚ΡŒ g.setColor( new Color(0, 0, 255, 128) ); g.fillRect( 0, getHeight()/3, getWidth(), getHeight()/3 ); } }; JPanel alphaComposite = new JPanel() { @Override public void paintComponent( Graphics g ) { Graphics2D g2d = (Graphics2D)g.create(); try { g2d.setColor( Color.WHITE ); g2d.fillRect( 0, 0, getWidth(), getHeight() ); g2d.setColor( Color.RED ); g2d.fillOval( 0, 0, getWidth(), getHeight() ); // ΠΊΠΎΠΌΠΏΠΎΠ·ΠΈΡ‚ SrcOver ΠΎΡ‚ΠΎΠ±Ρ€Π°ΠΆΠ°Π΅Ρ‚ исходноС ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ (src, // ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊ), ΠΏΠΎΠ²Π΅Ρ€Ρ… Ρ†Π΅Π»Π΅Π²ΠΎΠ³ΠΎ изобраТСния, с Π·Π°Π΄Π°Π½Π½ΠΎΠΉ // Π² derive( float ) alpha AlphaComposite composite = AlphaComposite.SrcOver.derive( 0.5f ); g2d.setComposite( composite ); g2d.setColor( Color.BLUE ); g2d.fillRect( 0, getHeight()/3, getWidth(), getHeight()/3 ); } finally { g2d.dispose(); } } }; JPanel content = new JPanel( new GridLayout( 1, 2 ) ); content.add( colorWithAlpha ); content.add( alphaComposite ); frame.setContentPane( content ); frame.setSize( 800, 600 ); frame.setVisible( true ); } public static void main(String[] args) throws IOException { EventQueue.invokeLater( Alpha::initUi ); } }