一、目标
绘制图形,通过设置属性改变颜色
二、效果
三、步骤
1. 在values下新建attrs.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="linecolor" format="color"/>
</declare-styleable>
</resources>
attr项为属性名称和格式
2. 新建继承自View的类CustomView.java
在构造方法获取属性
public CustomView(Context context, AttributeSet attrs){
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
try{
lineColor = a.getColor(R.styleable.CustomView_linecolor, Color.parseColor("#000000"));
}
finally {
init();
a.recycle();
}
}
重写onDraw()
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float centerX = getWidth()/2;
float centerY = getHeight()/2;
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(5);
canvas.drawCircle(centerX, centerY, 200, myPaint);
canvas.drawCircle(centerX-70, centerY-50, 40, myPaint);
canvas.drawCircle(centerX+70, centerY-50, 40, myPaint);
myPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(centerX-70, centerY-40, 25, myPaint);
canvas.drawCircle(centerX+70, centerY-40, 25, myPaint);
//drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)
RectF rectF = new RectF(centerX-80, centerY+20, centerX+80, centerY+100);
myPaint.setStyle(Paint.Style.STROKE);
canvas.drawArc(rectF, 0, 180, false, myPaint);
}
3. 引用控件
添加xmlns:custom="http://schemas.android.com/apk/res-auto"
<com.study.app.customview.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:linecolor="#DB6958"/>
参考: https://developer.android.com/training/custom-views/create-view.html
源代码 下载