gpt4 book ai didi

java - JPanel - 绘制一个不透明度为 50% 的黑色透明 png

转载 作者:行者123 更新时间:2023-11-30 02:31:58 27 4
gpt4 key购买 nike

让我用照片问我的问题:)

enter image description here

左边的图片是Adobe Photoshop中的透明照片,右边是我的java程序中的结果。我在重写的“paint(Graphics g)”方法的主体中使用了“drawImage”方法。我怎样才能让它看起来透明?看起来这里只能接受 0 或 100 透明度...

最佳答案

也许您正在寻找这样的东西:

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;

public class TransparentImage extends JPanel
{
private BufferedImage backImage, frontImage;
private float alpha = 1;

public TransparentImage()
{
try
{
// backImage = ImageIO.read(new File("mong.jpg") );
backImage = ImageIO.read(new File("grass.jpg") );
frontImage = ImageIO.read(new File("dukeWaveRed.gif") );
}
catch(Exception e)
{
System.out.println(e);
}
}

@Override
public Dimension getPreferredSize()
{
return new Dimension(backImage.getWidth(), backImage.getHeight());
}

public void setAlpha(float alpha)
{
this.alpha = alpha;
repaint();
}

@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);

// Paint background image

Graphics2D g2 = (Graphics2D) g;
int x = (getWidth() - backImage.getWidth())/2;
int y = (getHeight()- backImage.getHeight())/2;
g2.drawRenderedImage(backImage, AffineTransform.getTranslateInstance(x, y));

// Paint foreground image with appropriate alpha value

Composite old = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
x = (getWidth() - frontImage.getWidth())/2;
y = (getHeight()- frontImage.getHeight())/2;
g2.drawRenderedImage(frontImage, AffineTransform.getTranslateInstance(x, y));
g2.setComposite(old);
}

private static void createAndShowUI()
{
final TransparentImage app = new TransparentImage();

JSlider slider = new JSlider();
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
JSlider source = (JSlider) e.getSource();
app.setAlpha(source.getValue()/100f);
}
});
slider.setValue(100);

JFrame frame = new JFrame("Transparent Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( app );
frame.add(slider, BorderLayout.SOUTH);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}

public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

提供背景和前景图像。使用 slider 调整前景图像的 Alpha 值。

关于java - JPanel - 绘制一个不透明度为 50% 的黑色透明 png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44081774/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com