1. 程式人生 > >View工作原理(measure、layout、draw)

View工作原理(measure、layout、draw)

public class MyView extends View {
    private int myColor;
    private int r;
    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //屬性集合,第二個引數為attrs.xml檔案下<declare-styleable name="MyView">
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        //獲取到顏色的屬性,第二個引數為顏色預設值
        myColor = array.getColor(R.styleable.MyView_view_color, Color.parseColor("#29a6b6"));
        r= array.getDimensionPixelSize(R.styleable.MyView_view_r,10);
        //將TypedArray回收
        array.recycle();

    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int size = 400;
        if (heightMode==MeasureSpec.AT_MOST&&widthMode==MeasureSpec.AT_MOST){
            setMeasuredDimension(size,size);
        }else if(heightMode==MeasureSpec.AT_MOST){
            setMeasuredDimension(widthSize,size);
        }else if (widthMode==MeasureSpec.AT_MOST){
            setMeasuredDimension(size,heightSize);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int centX = getLeft()+r;//左邊的距離
        int centY = getTop()+getPaddingTop()+r;//上面的距離
        Paint paint = new Paint();
        paint.setColor(myColor);
        //開始繪製
        canvas.drawCircle(centX, centY, r, paint);
    }
}