需要自定义LineChartRenderer,相关代码如下
public class MaximumLineBarRenderer extends LineChartRenderer {
private float mMaxValue;
public MaximumLineBarRenderer(LineDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler) {
super(chart, animator, viewPortHandler);
}
public void setMaxValue(float maxValue){
mMaxValue = maxValue;
}
@Override
protected void drawCircles(Canvas c) {
LineDataSet dataSet = (LineDataSet) mChart.getLineData().getDataSetByIndex(0);
List<Entry> entries = dataSet.getEntries();
//找出曲线中yValue值最大的点
Entry maxYValueEntry = entries.get(0);
for (Entry entry : entries) {
if (entry.getY() > maxYValueEntry.getY()) {
maxYValueEntry = entry;
}
}
Transformer trans = mChart.getTransformer(dataSet.getAxisDependency());
MPPointD pointD = trans.getPixelForValues(maxYValueEntry.getX(), maxYValueEntry.getY());
mXBounds.set(mChart, dataSet);
String content = (int)maxYValueEntry.getY() + "分钟";
Paint bubblePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// bubblePaint.setColor(Color.parseColor("#244EA9FD"));
bubblePaint.setStyle(Paint.Style.FILL);
Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(Color.parseColor("#4EA9FD"));
textPaint.setStyle(Paint.Style.FILL);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(Utils.convertDpToPixel(15));
textPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
Rect rectTextBounds = new Rect();
textPaint.getTextBounds(content, 0, content.length(), rectTextBounds);
int contentWidth = rectTextBounds.right - rectTextBounds.left;
int contentHeight = rectTextBounds.bottom - rectTextBounds.top;
//文字左右和上下与气泡之间的间距
int offsetX = (int) Utils.convertDpToPixel(10);
int offsetY = (int) Utils.convertDpToPixel(5);
//整个气泡区域中心对应坐标
float centerX = (float) pointD.x;
float centerY = (float) (pointD.y - contentHeight / 2 - offsetY - Utils.convertDpToPixel(5));
//气泡区域的位置信息
RectF rectF = new RectF(centerX - contentWidth/2f - offsetX,
centerY - contentHeight / 2f - offsetY,
centerX + contentWidth / 2f + offsetX,
centerY + contentHeight / 2f + offsetY + 10);
Bitmap bubble = BitmapFactory.decodeResource(((LineChart)mChart).getContext().getResources(), R.drawable.bg_growth_report_chart_maximum);
c.drawBitmap(bubble, null, rectF, bubblePaint);
Paint.FontMetrics metrics = textPaint.getFontMetrics();
float top = metrics.top;
float bottom = metrics.bottom;
//气泡背景尖角的高度.px
int bitmapCuspHeight = 10;
int baseLineY = (int)(rectF.centerY() - bitmapCuspHeight / 2 - top / 2 - bottom / 2);
c.drawText(content, rectF.centerX(), baseLineY, textPaint);
}
}
网友评论