From:http://blog.csdn.net/jjdujiang/article/details/51811583
本周开发了Android画波形图,单击按钮,进入到新的activity,在新的activity中设置视图类setContentView(lineView),lineView是继承View,重载函数onDraw就可以在画布上画波形图了。
附上主要代码
- // 背景
- p.setStyle(Style.FILL);
- p.setColor(Color.WHITE);
- p.setStrokeWidth(1);
- canvas.drawRect(0, 0, width, height, p);
- // 图形区
- p.setStyle(Style.STROKE);
- p.setColor(Color.BLACK);
- canvas.drawRect(rectRect, p);
- // Y轴刻度
- p.setStyle(Style.FILL);
- for (int i = 0; i < strYScaleStrings.length; i++) {
- Integer yInteger = rectRect.top + i * rectRect.height() / (strYScaleStrings.length - 1);
- canvas.drawLine(rectRect.left, yInteger, rectRect.left - nInterInteger, yInteger, p);
- canvas.drawText(strYScaleStrings[i], nInterInteger, yInteger, p);
- }
- // X轴刻度
- for (int i = 0; i < strXScaleStrings.length; i++) {
- Integer xInteger = rectRect.left + i * rectRect.width() / (strYScaleStrings.length - 1);
- Integer xTextStartInteger = xInteger - rectXScaleWidthIntegers[i].width() / 2;
- canvas.drawLine(xInteger, rectRect.bottom, xInteger, rectRect.bottom + nInterInteger, p);
- canvas.drawText(strXScaleStrings[i], xTextStartInteger, height - rectXScaleWidthIntegers[i].height() / 2, p);
- }
- // X轴网格线
- p.setColor(Color.LTGRAY);
- p.setStrokeWidth(1);
- p.setPathEffect(effects);
- for (int i = 0; i < strXScaleStrings.length - 2; i++) {
- Integer xInteger = rectRect.left + (i + 1) * rectRect.width() / (strYScaleStrings.length - 1);
- canvas.drawLine(xInteger, rectRect.bottom, xInteger, rectRect.top, p);
- }
- // Y轴网格线
- for (int i = 0; i < strYScaleStrings.length - 2; i++) {
- Integer yInteger = rectRect.top + (i + 1) * rectRect.height() / (strYScaleStrings.length - 1);
- canvas.drawLine(rectRect.left, yInteger, rectRect.right, yInteger, p);
- }
- // 画曲线
- p.setStyle(Style.STROKE);
- p.setPathEffect(null);
- linePath.reset();
- for (int i = 0; i < nPointDrawCountInteger; i++) {
- double xValueDouble = (nPointStartInteger + i) / dbSampleFrequencyDouble;
- double yValueDouble = app.ch1ValueArrayDoubles[i];
- double dXInteger = rectRect.left +
- (xValueDouble - dbXMinDouble) * rectRect.width() / (dbXMaxDouble - dbXMinDouble);
- int nXInteger = (int)(dXInteger + 0.5);
- double dYIntegerDouble = rectRect.top +
- (yValueDouble - dbYMinDouble) * rectRect.height() / (dbYMaxDouble - dbYMinDouble);
- int nYInteger = (int)(dYIntegerDouble + 0.5);
- if (0 == i) {
- linePath.moveTo(nXInteger, nYInteger);
- } else {
- linePath.lineTo(nXInteger, nYInteger);
- }
- }
- p.setColor(Color.BLUE);
- p.setStrokeWidth(3); // 线条粗细
- canvas.drawPath(linePath, p);