RoundVIew的全部代码

RoundView.java代码:


/**
 * Created by lijiayi on 2017/3/5.
 */


public class RoundView extends View {
    // 圆形的颜色
    private int mColor;
    //视图的默认大小
    private final static int DEFAULT_SIZE = 200;
    //画圆形的画笔
    private Paint mPaint;

    public RoundView(Context context) {
        super(context);
        initPaint();
    }

    public RoundView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //他们两个是相同的
        //TypedArray array=context.getTheme().obtainStyledAttributes(attrs,R.styleable.RecyclerView,defStyleAttr,0);
        //获取RoundView中的所有自定义属性
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundView);
        //获取颜色的属性
        mColor = array.getColor(R.styleable.RoundView_round_color, Color.BLACK);
        //初始化画笔
        initPaint();
        //释放TypedArray
        array.recycle();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取测量之后的宽度
        int width = measureDimension(widthMeasureSpec);
        //获取测量之后的高度
        int height = measureDimension(heightMeasureSpec);
        //设置测量之后的大小
        setMeasuredDimension(width, height);

    }

    /**
     * 获取计算之后的值
     *
     * @param measureSpec
     * @return
     */
    private int measureDimension(int measureSpec) {
        //获取测量方式
        int specMode = MeasureSpec.getMode(measureSpec);
        //获取测量大小
        int specSize = MeasureSpec.getSize(measureSpec);
        //设置默认大小
        int result = DEFAULT_SIZE;
        //如果是wrap_content就选取最小的值作为最后测量的大小
        if (specMode == MeasureSpec.AT_MOST) {
            result = Math.min(DEFAULT_SIZE, specSize);
            //如果是match_parent或者是固定大小就返回测量的大小
        } else if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        }
        return result;
    }
    //初始化画笔
    private void initPaint() {
        mPaint = new Paint();
        //设置画笔的颜色 默认为黑色
        mPaint.setColor(mColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //获取布局的padding大小
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        //通过获取布局的宽高和padding大小计算实际的宽高
        int width = getWidth() - paddingLeft - paddingRight;
        int height = getHeight() - paddingTop - paddingBottom;
        //计算圆的半径
        int radius = Math.min(width, height) / 2;
        //以圆形的原点坐标,画出圆形
        canvas.drawCircle(paddingLeft + radius, paddingTop + radius, radius, mPaint);

    }

}

attrs_round_view.xml代码:



    
        
    

你可能感兴趣的:(RoundVIew的全部代码)