关于改变画笔透明度
public class test extends Panel implements Runnable{
private final static int WIDTH=800;
private final static int HEIGHT=480;
private Image test;
private float i;
private boolean add;
private Image screen;
public test(){
screen=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_ARGB);
test = Toolkit.getDefaultToolkit().getImage("test.png".intern());
Thread th=new Thread(this);
th.start();
i=0.0f;
add=true;
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,i));
System.out.println(i);
g2.drawImage(test,0,0,this);
g2.drawImage(screen, 0, 0, this);
}
public void update(Graphics g){
paint(g);
}
public static void main(String[] args) {
Frame frame = new Frame();
frame.setTitle("透明度测试");
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(new test());
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void run() {
while(true){
if(add){
if(i<=0.99f){
i+=0.01f;
}else{
add=false;
}
}else{
if(i>=0.01f){
i-=0.01f;
}else{
add=true;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
repaint();
}
}
}
为什么i值增加时效果可以看得很明显 图片渐渐显示出来 而减少时就毫无效果了 我想要的效果是图片渐渐出现然后又渐渐消失
------解决方案--------------------
我觉得你的逻辑有点问题,你用screen去覆盖的做法,没考虑如果panel的底就已经有很清晰的图片后,就效果不大了。
所以建议这么修改,首先在:
screen = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
后面,增加:
screen.getGraphics().fillRect(0, 0, WIDTH, HEIGHT); // 生成白色图片
然后将paint()函数中的:
g2.drawImage(screen, 0, 0, this); // 清除全背景
移动到:
Graphics2D g2 = (Graphics2D) g;
之后。
不过这种做法会导致闪烁,因为你全都是直接在Panel上画。
想不闪烁,做法应该是,先在某Image上(其实用screen就好了)清空,然后把test用透明度画上去,然后再把整个Image画到panel上,确保Panel上只会绘制1次。