改变图像不透明度

pas*_*aya 10 java animation resize image opacity

在项目中,我想同时调整大小并更改图像的不透明度.到目前为止,我认为我已经调整了大小.我使用这样定义的方法来完成大小调整:

public BufferedImage resizeImage(BufferedImage originalImage, int type){

    initialWidth += 10;
    initialHeight += 10;
    BufferedImage resizedImage = new BufferedImage(initialWidth, initialHeight, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, initialWidth, initialHeight, null);
    g.dispose();

    return resizedImage;
} 
Run Code Online (Sandbox Code Playgroud)

我从这里得到了这个代码.我无法找到解决方案的是改变不透明度.这就是我想知道该怎么做(如果可能的话).提前致谢.

更新:

我尝试使用此代码来显示一个圆形图片,其中透明的内部和外部(见下图)正在变得越来越不透明,但它不起作用.我不确定是什么问题.所有代码都在一个名为Animation的类中

public Animation() throws IOException{

    image = ImageIO.read(new File("circleAnimation.png"));
    initialWidth = 50;
    initialHeight = 50;
    opacity = 1;
}

public BufferedImage animateCircle(BufferedImage originalImage, int type){

      //The opacity exponentially decreases
      opacity *= 0.8;
      initialWidth += 10;
      initialHeight += 10;

      BufferedImage resizedImage = new BufferedImage(initialWidth, initialHeight, type);
      Graphics2D g = resizedImage.createGraphics();
      g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
      g.drawImage(originalImage, 0, 0, initialWidth, initialHeight, null);
      g.dispose();

      return resizedImage;

}
Run Code Online (Sandbox Code Playgroud)

我称之为:

Animation animate = new Animation();
int type = animate.image.getType() == 0? BufferedImage.TYPE_INT_ARGB : animate.image.getType();
BufferedImage newImage;
while(animate.opacity > 0){

    newImage = animate.animateCircle(animate.image, type);
    g.drawImage(newImage, 400, 350, this);

}
Run Code Online (Sandbox Code Playgroud)

小智 22

首先确保你传入方法的类型包含一个alpha通道,比如

BufferedImage.TYPE_INT_ARGB
Run Code Online (Sandbox Code Playgroud)

然后在绘制新图像之前,调用Graphics2D方法setComposite,如下所示:

float opacity = 0.5f;
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
Run Code Online (Sandbox Code Playgroud)

这会将绘图不透明度设置为50%.

  • 0 是透明的,1 是不透明的 (2认同)