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代碼:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundView">
<attr name="round_color" format="color" />
</declare-styleable>
</resources>