Android Color 顏色過度計算實現方法

在項目中經常要做一些動畫效果,一般會伴隨顏色的變化,爲了友好的交互,這個變化過程最好是平滑過度,這裏是貼上一種計算兩個顏色之間的色差在某個百分比情況的顏色值:

/**
	 * 計算從startColor過度到endColor過程中百分比爲franch時的顏色值
	 * @param startColor 起始顏色 int類型
	 * @param endColor 結束顏色 int類型
	 * @param franch franch 百分比0.5
	 * @return 返回int格式的color
	 */
	public static int caculateColor(int startColor, int endColor, float franch){
		String strStartColor = "#" + Integer.toHexString(startColor);
		String strEndColor = "#" + Integer.toHexString(endColor);
		return Color.parseColor(caculateColor(strStartColor, strEndColor, franch));
	}
	
	/**
	 * 計算從startColor過度到endColor過程中百分比爲franch時的顏色值
	 * @param startColor 起始顏色 (格式#FFFFFFFF)
	 * @param endColor 結束顏色 (格式#FFFFFFFF)
	 * @param franch 百分比0.5
	 * @return 返回String格式的color(格式#FFFFFFFF)
	 */
	public static String caculateColor(String startColor, String endColor, float franch){
		
		int startAlpha = Integer.parseInt(startColor.substring(1, 3), 16);
		int startRed = Integer.parseInt(startColor.substring(3, 5), 16);
		int startGreen = Integer.parseInt(startColor.substring(5, 7), 16);
		int startBlue = Integer.parseInt(startColor.substring(7), 16);
		
		int endAlpha = Integer.parseInt(endColor.substring(1, 3), 16);
		int endRed = Integer.parseInt(endColor.substring(3, 5), 16);
		int endGreen = Integer.parseInt(endColor.substring(5, 7), 16);
		int endBlue = Integer.parseInt(endColor.substring(7), 16);
		
		int currentAlpha = (int) ((endAlpha - startAlpha) * franch + startAlpha);
		int currentRed = (int) ((endRed - startRed) * franch + startRed);
		int currentGreen = (int) ((endGreen - startGreen) * franch + startGreen);
		int currentBlue = (int) ((endBlue - startBlue) * franch + startBlue);
		
		return "#" + getHexString(currentAlpha) + getHexString(currentRed)
				+ getHexString(currentGreen) + getHexString(currentBlue);
		
	}
	
	/** 
     * 將10進制顏色值轉換成16進制。 
     */  
	public static String getHexString(int value) {  
        String hexString = Integer.toHexString(value);  
        if (hexString.length() == 1) {  
            hexString = "0" + hexString;  
        }  
        return hexString;  
    }  


發佈了45 篇原創文章 · 獲贊 16 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章