1、线形图设置填充色为渐变色方法:
/*** Draws the provided path in filled mode with the provided drawable.** @param c* @param filledPath* @param drawable*/protected void drawFilledPath(Canvas c, Path filledPath, Drawable drawable) {if (clipPathSupported()) {c.save();c.clipPath(filledPath);drawable.setBounds((int) mViewPortHandler.contentLeft(),(int) mViewPortHandler.contentTop(),(int) mViewPortHandler.contentRight(),(int) mViewPortHandler.contentBottom());drawable.draw(c);c.restore();//在canvas上设置渐变色图片} else {throw new RuntimeException("Fill-drawables not (yet) supported below API level 18, " +"this code was run on API level " + Utils.getSDKInt() + ".");}}
渐变色图片:
最终效果:
具体代码参见:MPChartLibrary开源项目中的 LineRadarRenderer.class类
2、为canvas背景设置渐变色
final Drawable drawable = dataSet.getFillDrawable();c.save();drawable.setBounds((int) mViewPortHandler.contentLeft(),(int) mViewPortHandler.contentTop(),(int) mViewPortHandler.contentRight(),(int) mViewPortHandler.contentBottom());drawable.draw(c);// mRenderPaint.setColor(dataSet.getColor());for (int j = 0; j < buffer.size(); j += 4) {if (!mViewPortHandler.isInBoundsLeft(buffer.buffer[j + 2]))continue;if (!mViewPortHandler.isInBoundsRight(buffer.buffer[j]))break;c.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],buffer.buffer[j + 3], mRenderPaint);if (drawBorder) {c.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],buffer.buffer[j + 3], mBarBorderPaint);}}c.restore();
效果图:看后面背景
代码初步是在 BarChartRenderer.class中做了修改。并且在 BaseDataSet.class中添加了两个接口
public Drawable getFillDrawable() {return mFillDrawable;}/*** Sets the drawable to be used to fill the area below the line.** @param drawable*/@TargetApi(18)public void setFillDrawable(Drawable drawable) {this.mFillDrawable = drawable;}
大致是这样的修改的。具体可再优化。
3、为柱状图每个元素设置渐变色
for (int j = 0; j < buffer.size(); j += 4) {if (!mViewPortHandler.isInBoundsLeft(buffer.buffer[j + 2]))continue;if (!mViewPortHandler.isInBoundsRight(buffer.buffer[j]))break;//设置柱状图的颜色为渐变色LinearGradient linearGradient = new LinearGradient(0, 0, 0, 2000,Color.GREEN, Color.WHITE, Shader.TileMode.CLAMP);mRenderPaint.setShader(linearGradient);//目标Paint即为绘制柱的Paintc.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],buffer.buffer[j + 3], mRenderPaint);if (drawBorder) {c.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],buffer.buffer[j + 3], mBarBorderPaint);}}
效果图:
代码初步是在 BarChartRenderer.class中做了修改。