您的位置:首页 > 编程语言 > Java开发

在JAVA Swing实现倒影效果

2011-09-22 20:15 281 查看
在JAVA中要实现一幅图片的倒影效果有两种方法。第一种方法是得到图片的所有像素并将其颠倒显示,再对每个像素的Alpha值进行计算以产生一种由半透明至全透明的渐变效果。这种方法用代码实现起来较为复杂,而且数学功底也要好,但彻底掌握其编程方法后能非常方便的运用于其他的编程语言中,不过在JAVA中其运行效率并不高。而第二种方法就是使用JAVA的图像合成效果,可以非常方便的实现图片的倒影。所以如果没有特别要求(比如游戏制作)的话完全可以使用第二种方法。

以下的程序代码来自《JAVA动画、图形和极富客户端效果开发》一书里的例子。当然我并不是完全照书上的代码抄,而是按我的意愿改写了一番,就当练练手,呵呵,而且我觉得那本书把“倒影”一词翻译成“反射”并不合适,毕竟反射一词也是JAVA里的一种技术名词,虽然只要是认真看书的人都不会产生混合,但咱们天朝的词汇博大精深,完全可以避免这种混乱。

好了不多了,直接放上代码大家一起瞧瞧。

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ImageFrame extends JFrame
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{

public void run()
{
new ImageFrame();
}

});
}

public ImageFrame()
{
this.setTitle("倒影效果");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(new InvertedImagePanel());
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}

}

class InvertedImagePanel extends JPanel
{
public static final String IMAGEURL = "logoleaf.JPG";
private Image image = null;
private Image invertedImage = null;

public InvertedImagePanel()
{
// 载入一张原始图片
image = new ImageIcon(IMAGEURL).getImage();
int width = image.getWidth(null);
int height = image.getHeight(null);
this.setPreferredSize(new Dimension(width + 10, height * 2 + 15));
this.setBackground(Color.black);

invertedImage = getInvertedImage(image, 100, 255);
}

public Image getInvertedImage(Image img, int start, int end)
{
// 得到原始图片宽和高
int imgWidth = img.getWidth(null);
int imgHeight = img.getHeight(null);
// 创建一个BufferedImage图像类对象
BufferedImage invertedImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D) invertedImage.getGraphics();
// 将原始图像倒置输出到图像类
g2.drawImage(img, 0, 0, imgWidth, imgHeight, 0, imgHeight, imgWidth, 0, null);
// 创建一个由透明到不透明的渐变用以图像合成
Color c1 = new Color(0, 0, 0, start);
Color c2 = new Color(0, 0, 0, end);
GradientPaint mask = new GradientPaint(0, 0, c1, 0, imgHeight, c2);
g2.setPaint(mask);
// 合成图像
g2.setComposite(AlphaComposite.DstOut);
g2.fillRect(0, 0, imgWidth, imgHeight);
g2.dispose();
return invertedImage;
}

protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
GradientPaint gp = new GradientPaint(0, 0, new Color(0, 0, 0), getWidth(), getHeight(), new Color(0, 100, 200));
g2.setPaint(gp);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.drawImage(image, 5, 5, null);
g2.drawImage(invertedImage, 5, image.getHeight(null) + 10, null);
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: