自定义View之折线图

来源:互联网 发布:99手机游戏java 编辑:程序博客网 时间:2024/05/29 09:15
public class CustomView extends View{private Paint linePaint;private Paint linePaint2;private Paint textPaint;private Path mPath;private float textSize=10;public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);// TODO Auto-generated constructor stub} public CustomView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stublinePaint=new Paint();linePaint2=new Paint();textPaint=new Paint();}public CustomView(Context context) {super(context);// TODO Auto-generated constructor stub}/** * 0,20,-25,30,0,24,27 * */@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);int base_x = (getWidth()-20)/7;//将y轴分成60份,每份代表1℃,最高温度为60,最低温度为-60int base_y=(getHeight()/120);linePaint.setColor(Color.RED);        linePaint.setStyle(Paint.Style.STROKE);          linePaint.setStrokeWidth(1);        linePaint.setAntiAlias(true);        linePaint2.setColor(Color.BLUE);        linePaint2.setStyle(Paint.Style.STROKE);          linePaint2.setStrokeWidth(1);        linePaint2.setAntiAlias(true);        textPaint.setAntiAlias(true);        textPaint.setTextSize(10);        textPaint.setStyle(Style.STROKE);        textPaint.setColor(Color.BLACK);        //画坐标        mPath = new Path();        mPath.moveTo(10, getTop()+10);          mPath.lineTo(10, getBottom()-20);          mPath.lineTo(getRight()-10, getBottom()-20);        //画0°基坐标        Path path=new Path();        path.moveTo(10, getHeight()/2);        path.lineTo(20, getHeight()/2);        canvas.drawPath(path, linePaint);        canvas.drawPath(mPath, linePaint);        //画折线图        Path path2=new Path();        path2.moveTo(base_x, base_y*0+getHeight()/2);        path2.lineTo(base_x*2, base_y*(60-20));        path2.lineTo(base_x*3, base_y*25+getHeight()/2);        path2.lineTo(base_x*4, base_y*30);        path2.lineTo(base_x*5, base_y*0+getHeight()/2);        path2.lineTo(base_x*6, base_y*36);        path2.lineTo(base_x*7, base_y*33);        canvas.drawPath(path2, linePaint2);        canvas.drawText("0", 20+textSize/2, getHeight()/2+textSize/2, textPaint);canvas.drawText("周一", base_x, getBottom()-textSize/2, textPaint);        canvas.drawText("周二", base_x*2, getBottom()-textSize/2, textPaint);        canvas.drawText("周三", base_x*3, getBottom()-textSize/2, textPaint);        canvas.drawText("周四", base_x*4, getBottom()-textSize/2, textPaint);        canvas.drawText("周五", base_x*5, getBottom()-textSize/2, textPaint);        canvas.drawText("周六", base_x*6, getBottom()-textSize/2, textPaint);        canvas.drawText("周日", (base_x*7), getBottom()-textSize/2, textPaint);}}

0 0
原创粉丝点击