2011-10-15 37 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

相关问题