一个简单的自定义View(条形图)

package com.bawei.week1;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Mir_you on 2018/9/1.
 */

public class You extends View {

    private int wmode;
    private int hmode;
    private int wsize;
    private int hsize;

    public Su(Context context) {
        super(context);
    }

    public Su(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public Su(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        wmode = MeasureSpec.getMode(widthMeasureSpec);
        hmode = MeasureSpec.getMode(heightMeasureSpec);
        wsize = MeasureSpec.getSize(widthMeasureSpec);
        hsize = MeasureSpec.getSize(heightMeasureSpec);
        if (wmode == MeasureSpec.AT_MOST && hmode == MeasureSpec.AT_MOST){
            setMeasuredDimension(wsize,hsize);
        }else if (wmode == MeasureSpec.AT_MOST){
            setMeasuredDimension(wsize,450);
        }else if (hmode == MeasureSpec.AT_MOST){
            setMeasuredDimension(450,hsize);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint paint = new Paint();
        paint.setTextSize(20);

        paint.setColor(Color.RED);

        for (int i = 0; i < 5; i++) {
            canvas.drawLine(0,100*i,wsize,100*i,paint);
        }
        for (int i = 0; i < 8; i++) {
            canvas.drawLine(100*i,0,100*i,400,paint);
        }
        int j = 1;
        for (int i = 0; i < 7; i++) {
            canvas.drawRect(10+(100 * i),20+(50 * i),90+(100 * i),400,paint);
            canvas.drawText(5000-(500 * i)+"",20+(100 * i),50 * i,paint);

            canvas.drawText("周"+j,20+(100 * i),420,paint);
            j++;
        }


    }
}
 

猜你喜欢

转载自blog.csdn.net/Mir_you/article/details/82317810

相关文章