在java中创建alpha图像
我即将开始一个项目的工作,该项目将生成一些带有alpha(渐变)的PNG,并希望在java中以编程方式绘制它们 对于(一个简单的)示例,我想画一个方框,添加一个阴影,然后将其保存到一个PNG文件中,然后可以覆盖到其他图形上在java中创建alpha图像,java,java-2d,Java,Java 2d,我即将开始一个项目的工作,该项目将生成一些带有alpha(渐变)的PNG,并希望在java中以编程方式绘制它们 对于(一个简单的)示例,我想画一个方框,添加一个阴影,然后将其保存到一个PNG文件中,然后可以覆盖到其他图形上 标准JRE系统库是否可以实现这一点 哪些库可以简化这种操作 谢谢 标准JRE系统库是否可以实现这一点 是的,这是可能的,而且非常简单。下面的代码生成此图像(透明png): publicstaticvoidmain(字符串[]args)引发IOException{ int x
publicstaticvoidmain(字符串[]args)引发IOException{
int x=50,y=50,w=300,h=200;
//画“影子”
BuffereImage img=新的BuffereImage(400300,BuffereImage.TYPE_INT_ARGB);
Graphics g=img.getGraphics();
g、 设置颜色(颜色为黑色);
g、 fillRect(x+10,y+10,w,h);
//模糊阴影
BuffereImage op=getBlurredOp();
img=op.filter(img,null);
//画盒子
g=img.getGraphics();
g、 setColor(Color.RED);
g、 fillRect(x,y,w,h);
//将其写入磁盘
write(img,“png”,新文件(“test.png”);
}
专用静态缓冲区ImageOp getBlurredOp(){
浮动[]矩阵=新浮动[400];
对于(int i=0;i<400;i++)
矩阵[i]=1.0f/400.0f;
返回新的卷积运算(新内核(20,20,矩阵),
卷积运算。边(无运算,空);
}
哪些库可以简化这种操作
我认为这取决于您的其他用例。对于简单的形状,如长方体和椭圆形,我会选择上面的解决方案,不需要库。这里有一个关于java中alpha掩码的问题,谢谢Jeffry,我已经到了……还没有找到阴影部分,如果有人可以点击一个示例,我会打勾……很好的答案,我找到了这个博客和库(浏览一下)对于模糊/投影非常有用。
public static void main(String[] args) throws IOException {
int x = 50, y = 50, w = 300, h = 200;
// draw the "shadow"
BufferedImage img = new BufferedImage(400, 300, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
g.setColor(Color.BLACK);
g.fillRect(x + 10, y + 10, w, h);
// blur the shadow
BufferedImageOp op = getBlurredOp();
img = op.filter(img, null);
// draw the box
g = img.getGraphics();
g.setColor(Color.RED);
g.fillRect(x, y, w, h);
// write it to disk
ImageIO.write(img, "png", new File("test.png"));
}
private static BufferedImageOp getBlurredOp() {
float[] matrix = new float[400];
for (int i = 0; i < 400; i++)
matrix[i] = 1.0f/400.0f;
return new ConvolveOp(new Kernel(20, 20, matrix),
ConvolveOp.EDGE_NO_OP, null);
}