上面是效果图,下面看代码,都有注释:
package com.example.customeview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import java.util.ArrayList;
/**
* 自定义柱状图
*/
public class MyCustomCylinderView extends View {
private Paint paint;
private ArrayList<Integer> mHeightList = new ArrayList<>();
public MyCustomCylinderView(Context context) {
super(context);
}
public MyCustomCylinderView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
}
public MyCustomCylinderView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStrokeWidth(2);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setDither(true);
//先画坐标
//X轴
/**
* 画X轴
* 参数分别是:起始X轴坐标、Y轴坐标,终止X轴坐标、Y轴坐标,画笔
* X轴:起始终止的Y轴坐标值不变
*/
canvas.drawLine(50, 550, 850, 550, paint);
/**
* X轴的右边小箭头
* 此处需要找到X轴的终止处的X、Y坐标值,也就是上面代码的(850,550)
* 然后以此坐标为起始点分别画两条斜线
* 这里就完成了X轴
*/
canvas.drawLine(850, 550, 840, 540, paint);
canvas.drawLine(850, 550, 840, 560, paint);
/**
* 同理再画Y轴
* Y轴X轴坐标值不变
*/
canvas.drawLine(50, 550, 50, 50, paint);
canvas.drawLine(50, 50, 40, 60, paint);
canvas.drawLine(50, 50, 60, 60, paint);
/**
* 画圆柱体
* 其实就是矩形
* 宽width = right - left
* 高height = bottom - top
* 宽固定为50
*/
paint.setColor(Color.RED);
paint.setTextSize(30);
if (mHeightList.size() != 0)
for (int i = 0; i < mHeightList.size(); i++) {
RectF rectF = new RectF(150 + 100*i, 550 - mHeightList.get(i), 100 + 100*i, 550);
canvas.drawRect(rectF, paint);
canvas.drawText(mHeightList.get(i) + "" , 100 + 100 *i, 540 - mHeightList.get(i),paint);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void setmHeightList(ArrayList<Integer> heightList){
mHeightList = heightList;
postInvalidate();
}
}
布局中代码:
<com.example.customeview.MyCustomCylinderView
android:id="@+id/cylinder_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
在Activity中设置数值:
package com.example.customeview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.util.ArrayList;
public class CylinderActivity extends AppCompatActivity {
private MyCustomCylinderView CylinderView;
private ArrayList<Integer> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cylinder);
CylinderView = findViewById(R.id.cylinder_view);
list.add(200);
list.add(400);
list.add(500);
list.add(100);
list.add(20);
list.add(250);
list.add(30);
CylinderView.setmHeightList(list);
}
}
这样就完成了柱状图的实现了,是不是很简单。