在项目中,我想同时调整大小并更改图像的不透明度。到目前为止,我认为我已经调整了大小。我使用这样定义的方法来完成大小调整:
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;
}
我从这里得到了这个代码。我无法找到解决方案的是改变不透明度。这就是我想知道该怎么做(如果可能的话)。提前谢谢。
更新:
我尝试使用此代码来显示一个圆形图片,其中透明的内部和外部(见下图)正在变得越来越不透明,但它不起作用。我不确定是什么问题。所有代码都在一个名为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;
}
我称之为:
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);
}
答案 0 :(得分:20)
首先确保您传入方法的类型包含Alpha通道,例如
BufferedImage.TYPE_INT_ARGB
然后在绘制新图像之前,像这样调用Graphics2D方法setComposite:
float opacity = 0.5f;
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
将绘图不透明度设置为50%。