以下代码会实现自定义的圆,圆的颜色可以设定,并且宽/高支持具体大小,martch_parent以及wrap_content,控件也支持padding属性的设置。
自定义view:
public class CircleView extends View {
private Context mContext;
private int mColor;
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public CircleView(Context context) {
super(context);
this.mContext = context;
init();
}
public CircleView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
init();
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
// 根据自定义类型设定颜色
TypedArray circlrColor = mContext.obtainStyledAttributes(attrs,
R.styleable.CircleView);
mColor = circlrColor.getColor(styleable.CircleView_circle_color,
Color.RED);
init();
}
private void init() {
mPaint.setColor(mColor);
}
@Overrideprotected
void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
// 在wrap_content的情况下默认长度为200dp
int minSize = DisplayUtil.dip2px(mContext, 200);
// wrap_content的specMode是AT_MOST模式,这种情况下宽/高等同于specSize
// 查表得这种情况下specSize等同于parentSize,也就是父容器当前剩余的大小
// 在wrap_content的情况下如果特殊处理,效果等同martch_parent
if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(minSize, minSize);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(minSize, heightSpecSize);
} else if (heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSpecSize, minSize);
}
}
@Overrideprotected
void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 处理padding属性
final int paddingLeft = getPaddingLeft();
final int paddingTop = getPaddingTop();
final int paddingRight = getPaddingRight();
final int paddingBottom = getPaddingBottom();
int width = getWidth() - paddingLeft - paddingRight;
int height = getHeight() - paddingTop - paddingBottom;
int radius = Math.min(width, height) / 2;
canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint);
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.view.CircleView
android:id="@+id/circleView1"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_margin="20dp"
android:background="#000000"
android:padding="20dp"
app:circle_color="@color/main_color" />
</LinearLayout>
在attrs.xml文件中设置自定义属性:
<declare-styleable name="CircleView">
<attr name="circle_color" format="color" />
</declare-styleable>
关于自定义view中的dp到px的单位转换,请参考另一篇博文:http://blog.csdn.net/myfwjy/article/details/51766646
整体效果: