Android实现动态数据图表




package com.example.sadsa;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;

public class ChartViewDemo3 extends View {

	private final Path mPath = new Path();
	private Paint mPaint = new Paint();
	private int max = 200;
	private int overTop = 340;
	private int[] lineValue = new int[9];

	public ChartViewDemo3(Context context, AttributeSet attrs) {
		super(context, attrs);

		mPaint.setColor(Color.WHITE);

		mPaint.setStrokeWidth(2.0f);

		mPaint.setAntiAlias(true);

		mPaint.setStyle(Style.STROKE);

		mPaint.setTextSize(15);
	}

	public void setMax(int max) {
		this.max = max;
	}

	/****
	 * 更新
	 * 
	 * @param value
	 *            获取到的新值
	 */
	public void update(int value) {
		for (int i = 0; i < lineValue.length - 1; i++) {

			lineValue[i] = lineValue[i + 1];

		}
		lineValue[lineValue.length - 1] = value;
		invalidate();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		int x = getWidth() / (lineValue.length + 1);// 起始的X轴坐标
		mPath.reset();
		mPath.moveTo(x, getOverTop(0));
		for (int i = 1; i < lineValue.length; i++) {
			mPath.lineTo(x * (i + 1), getOverTop(i));
		}
		canvas.drawPath(mPath, mPaint);
		Bitmap bitmap1 = ((BitmapDrawable) getResources().getDrawable(
				R.drawable.point)).getBitmap();
		Bitmap bitmap2 = ((BitmapDrawable) getResources().getDrawable(
				R.drawable.point_)).getBitmap();
		for (int i = 0; i < lineValue.length; i++) {
			canvas.drawText(lineValue[i] + "", x * (i + 1) - 10,
					getOverTop(i) - 10, mPaint);

			if (lineValue[i] < max) {
				canvas.drawBitmap(bitmap1,
						x * (i + 1) - bitmap1.getWidth() / 2, getOverTop(i)
								- bitmap1.getHeight() / 2, mPaint);
			} else {
				canvas.drawBitmap(bitmap2,
						x * (i + 1) - bitmap2.getWidth() / 2, getOverTop(i)
								- bitmap2.getHeight() / 2, mPaint);

			}
		}
	}

	public float getOverTop(int i) {
		return (overTop - (lineValue[i] > 1000 ? 1000
				: lineValue[i] * 333 / 1000));
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值