Android自定义View模拟并实现3D柱状图

先看效果图

Android自定义View模拟并实现3D柱状图_第1张图片

呈上代码:

  • 自定义View类
public class MyBarView extends View {
    private Paint barPaint;                             //柱状图画笔
    private Paint shadowPaint;                          //阴影画笔
    private int xOffset=1,yOffset=1;                    //x和y方向的偏移量
    private int startX=100,startY=400,endX=200,endY=1000;
    private int layerNum=25;                            //画布的层数
    private int barMargin=50;                           //每个柱状体之前的间隔
    private List percents=new ArrayList<>(); //每种数据的数值,用于计算比例,画出柱状体高度
    private int perSum;                                 //每种数据数值的总和
    public MyBarView(Context context,int... pers){
        super(context);
        for(int i=0;i=1;j--){       //从后往前画
                canvas.drawRect(startX+xOffset*j,nowStartY-yOffset*j,endX+xOffset*j,endY-yOffset*j,barPaint);
                if(j==1||j==layerNum)           //画阴影
                    canvas.drawRect(startX+xOffset*j,nowStartY-yOffset*j,endX+xOffset*j,endY-yOffset*j,shadowPaint);
            }
            int length=endX-startX;     //矩形边长
            startX+=length+barMargin;   //计算下一个柱状体的左上角x点的值
            endX+=length+barMargin;     //计算下一个柱状体的右下角x点的值
        }
    }

    private void init(){    //初始化控件
        barPaint=new Paint();
        barPaint.setStyle(Paint.Style.FILL);
        barPaint.setColor(Color.RED);

        shadowPaint=new Paint();
        shadowPaint.setStyle(Paint.Style.STROKE);
        shadowPaint.setStrokeWidth(1);
        shadowPaint.setColor(Color.parseColor("#515151"));
    }
}
  • MainActivity中创建该View
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView(){
        MyBarView myBarView=new MyBarView(this,10,20,30,50,60,80);
        ((FrameLayout)(findViewById(R.id.frame))).addView(myBarView);
    }

}
  • 最后是布局文件


    

 

你可能感兴趣的:(Android,android,canvas,安卓)