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
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 ); } } |