1. 程式人生 > >Java Graphics2D繪製背景透明的圖形過程

Java Graphics2D繪製背景透明的圖形過程

package com.jhy.time;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class DrawTransparentPic {

	
	/**
	 * 純繪製圖形,其背景是黑色的
	 * @param args
	 * @throws IOException
	 */
	public void drawImage() throws IOException{
		int width=256;
		int height=256;
		//建立BufferedImage物件
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		// 獲取Graphics2D 
		Graphics2D g2d = bi.createGraphics();
		
		// 畫圖BasicStroke是JDK中提供的一個基本的畫筆類,我們對他設定畫筆的粗細,就可以在drawPanel上任意畫出自己想要的圖形了。
		g2d.setColor(new Color(255, 0, 0));
		g2d.setStroke(new BasicStroke(1f));
		g2d.fillRect(128, 128, width, height);
		
		// 釋放物件
		g2d.dispose();
		
		// 儲存檔案
		ImageIO.write(bi, "png", new File("H:/test.png"));
	}
	
	/**
	 * 繪製圖形,把自己繪製的圖形設定為透明或半透明,背景並不透明   前景透明,背景依然是黑色
	 * @param args
	 * @throws IOException
	 */
	public static void drawImage1() throws IOException{
		int width=256;
		int height=256;
		//建立BufferedImage物件
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 獲取Graphics2D 
		Graphics2D g2d = bi.createGraphics();
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));// 1.0f為透明度 ,值從0-1.0,依次變得不透明 
		
		// 畫圖BasicStroke是JDK中提供的一個基本的畫筆類,我們對他設定畫筆的粗細,就可以在drawPanel上任意畫出自己想要的圖形了。
		g2d.setColor(new Color(255, 0, 0));
		g2d.setStroke(new BasicStroke(1f));
		g2d.fillRect(128, 128, width, height);
		
		// 釋放物件 透明度設定結束
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
		g2d.dispose();
		
		// 儲存檔案
		ImageIO.write(bi, "png", new File("H:/test.png"));
	}
	
	/**
	 * 繪製透明圖形
	 * @param args
	 * @throws IOException
	 */
	public static void drawTransparent() throws IOException{
		int width=256;
		int height=256;
		//建立BufferedImage物件
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 獲取Graphics2D 
		Graphics2D g2d = image.createGraphics();
		
		// 增加下面程式碼使得背景透明
		image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
		g2d.dispose();
		g2d = image.createGraphics();
		// 背景透明程式碼結束
		
		// 畫圖BasicStroke是JDK中提供的一個基本的畫筆類,我們對他設定畫筆的粗細,就可以在drawPanel上任意畫出自己想要的圖形了。
		g2d.setColor(new Color(255, 0, 0));
		g2d.setStroke(new BasicStroke(1f));
		g2d.fillRect(128, 128, width, height);
		
		// 釋放物件
		g2d.dispose();
		
		// 儲存檔案
		ImageIO.write(image, "png", new File("H:/test.png"));
	}
	
	public static void main(String[] args) throws IOException {
//		drawTransparent();
		drawImage1();
		
	}

}