package bw.com.bw_day04.demo05; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; /** * 柱状图 -- 继承View */ public class CustomView05 extends View{ private Paint paint;//画笔 private int rect_width = 30;//柱子的宽度 private int rect_space = 20;//柱子的间隔 //TODO 柱子的颜色 + 柱子的高度 --- 可以从别的地方获取(网络获取) private int[][] rects = {{Color.RED,300},{Color.GREEN,400},{Color.BLUE,500},{Color.YELLOW,600}}; public CustomView05(Context context) { super(context); } public CustomView05(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //初始化画笔 paint = new Paint(); paint.setStrokeWidth(5); paint.setAntiAlias(true); //绘制柱子 if(rects!=null) { for(int i = 0;i<rects.length;i++) { //修改画笔 paint.setColor(rects[i][0]); //绘制矩形 int left = 50+rect_space+(rect_width+rect_space)*i; int top = getHeight() - 50 - rects[i][1]; canvas.drawRect(left,top,left+rect_width,getHeight()-50,paint); } } paint.setColor(Color.BLACK); //绘制X轴 canvas.drawLine(50,getHeight()-50,getWidth()-50,getHeight()-50,paint); canvas.drawLine(getWidth()-50,getHeight()-50,getWidth()-75,getHeight()-75,paint); canvas.drawLine(getWidth()-50,getHeight()-50,getWidth()-75,getHeight()-25,paint); //绘制Y轴 canvas.drawLine(50,getHeight()-50,50,50,paint); canvas.drawLine(50,50,25,75,paint); canvas.drawLine(50,50,75,75,paint); //绘制XY的交汇 canvas.drawCircle(50,getHeight()-50,5,paint); //绘制300对应的点 canvas.drawCircle(50,getHeight()-350,5,paint); //绘制300的文字 paint.setTextSize(30); canvas.drawText("300",10,getHeight()-350,paint); } }