2011-10-15 40 views
7

在Android中我想用動態數量的餅圖繪製PieChart。每個餅圖應該具有與漸變不同的顏色。如何從Android上的梯度以編程方式獲取顏色列表

例如,我想要從淺棕色到深棕色的漸變。如果我需要畫五張餡餅,那麼我需要從這個漸變的開始到結束五個菜單。

我該怎麼用Java框架來做到這一點?

我發現我可以創建一條線的LinearGradient,即:

LinearGradient lg = new LinearGradient(1, 1, 5, 5, toRGB("lightbrown"), toRGB("darkbrown"), TileMode.REPEAT); 

但我沒有發現任何函數從該行獲得了顏色,即:

// for the five needed RGB colors from the gradient line 
lg.getRGBColor(1, 1); 
lg.getRGBColor(2, 2); 
lg.getRGBColor(3, 3); 
lg.getRGBColor(4, 4); 
lg.getRGBColor(5, 5); 

你有什麼想法,我怎麼能得到這個?

謝謝!

回答

16

您無法直接從LinearGradient獲取這些值。該漸變不包含實際的繪圖。要獲得這些值,可以將它們繪製到畫布上,並將顏色從畫布中拉出,或者我建議自己計算這些值。

這是一個重複的五個步驟中的線性漸變,並且具有第一個和最後一個顏色的RGB值。其餘的只是數學。這裏的僞代碼:

int r1 = startColor.red; 
int g1 = startColor.green; 
int b1 = startColor.blue; 

int r2 = endColor.red; 
int g2 = endColor.green; 
int b2 = endColor.blue; 

int redStep = r2 - r1/4; 
int greenStep = g2 - g1/4; 
int blueStep = b2 - b1/4; 

firstColor = new Color(r1, g1, b1); 
secondColor = new Color(r1 + redStep, g1 + greenStep, b1 + blueStep); 
thirdColor = new Color(r1 + redStep * 2, g1 + greenStep * 2, b1 + blueStep * 2); 
fourthColor = new Color(r1 + redStep * 3, g1 + greenStep * 3, b1 + blueStep * 3); 
fifthColor = new Color(r1 + redStep * 4, g1 + greenStep * 4, b1 + blueStep * 4); 
+0

非常好。簡單的想法和工作方案!謝謝 – treimy

+0

謝謝你這個簡單而好主意! – Gatekeeper

3

另一種方法是有點更可重用(我似乎碰到這個問題所有的時間)。這是更多的代碼。下面是用法:

int[] colors = {toRGB("lightbrown"), toRGB("darkbrown")};//assuming toRGB : String -> Int 
    float[] positions = {1, 5}; 
    getColorFromGradient(colors, positions, 1) 
    //... 
    getColorFromGradient(colors, positions, 5) 

支持功能

public static int getColorFromGradient(int[] colors, float[] positions, float v){ 

    if(colors.length == 0 || colors.length != positions.length){ 
     throw new IllegalArgumentException(); 
    } 

    if(colors.length == 1){ 
     return colors[0]; 
    } 

    if(v <= positions[0]) { 
     return colors[0]; 
    } 

    if(v >= positions[positions.length-1]) { 
     return colors[positions.length-1]; 
    } 

    for(int i = 1; i < positions.length; ++i){ 
     if(v <= positions[i]){ 
      float t = (v - positions[i-1])/(positions[i] - positions[i-1]); 
      return lerpColor(colors[i-1], colors[i], t); 
     } 
    } 

    //should never make it here 
    throw new RuntimeException(); 
} 

public static int lerpColor(int colorA, int colorB, float t){ 
    int alpha = (int)Math.floor(Color.alpha(colorA) * (1 - t) + Color.alpha(colorB) * t); 
    int red = (int)Math.floor(Color.red(colorA) * (1 - t) + Color.red(colorB) * t); 
    int green = (int)Math.floor(Color.green(colorA) * (1 - t) + Color.green(colorB) * t); 
    int blue = (int)Math.floor(Color.blue(colorA) * (1 - t) + Color.blue(colorB) * t); 

    return Color.argb(alpha, red, green, blue); 
} 
+0

有用的動態calucalation – Godwin

相關問題