tre*_*imy 7 android gradient list colors
在Android中我想绘制一个动态数量的馅饼PieChart.每个饼应该具有与渐变不同的颜色.
例如,我想要从浅棕色到深棕色的渐变.如果我需要画五个馅饼,我需要从这个渐变的开始到结束五个卷.
如何使用Android框架在Java中实现这一目标?
我发现我可以为一条线创建一个LinearGradient,即:
LinearGradient lg = new LinearGradient(1, 1, 5, 5, toRGB("lightbrown"), toRGB("darkbrown"), TileMode.REPEAT);
Run Code Online (Sandbox Code Playgroud)
但我没有找到任何从这一行获得颜色的功能,即:
// 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);
Run Code Online (Sandbox Code Playgroud)
你有什么想法我怎么能得到这个?
谢谢!
spa*_*nia 17
您无法直接从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);
Run Code Online (Sandbox Code Playgroud)
另一种可重用的方法(我似乎一直都在碰到这个问题)。还有更多代码。这是用法:
int[] colors = {toRGB("lightbrown"), toRGB("darkbrown")};//assuming toRGB : String -> Int
float[] positions = {1, 5};
getColorFromGradient( colors, positions, 1 )
//...
getColorFromGradient( colors, positions, 5 )
Run Code Online (Sandbox Code Playgroud)
配套功能
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);
}
Run Code Online (Sandbox Code Playgroud)