本文主要簡述一下如何使用BufferedImage進行漸變色操做。java
java/awt/GradientPaint.javacode
public class GradientPaint implements Paint { Point2D.Float p1; Point2D.Float p2; Color color1; Color color2; boolean cyclic; //...... }
這個是生成漸變色的關鍵類,固然也有其餘的漸變類,好比
java/awt/LinearGradientPaint.javaci
public static BufferedImage drawGradient(BufferedImage srcImg, int startX, int startY, int endX, int endY, Color colorFrom, Color colorTo, float opacity) { BufferedImage dstImg = new BufferedImage(srcImg.getWidth(), srcImg.getHeight(), BufferedImage.TYPE_INT_RGB); GradientPaint grad = new GradientPaint(startX, startY, colorFrom, endX, endY, colorTo); //從左上到右下漸變; Graphics2D g2 = (Graphics2D) dstImg.getGraphics(); g2.setPaint(grad); g2.fillRect(startX, startY, endX, endY); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, opacity)); g2.drawImage(srcImg, 0, 0, srcImg.getWidth(), srcImg.getHeight(), null); g2.dispose(); return dstImg; }
原理就是先使用GradientPaint畫一個漸變色的矩形,而後將原圖使用必定透明度覆蓋上去,這樣就看出漸變。
不足以後的話,就是漸變顏色會偏淡。get