package com.bw.u.liangweihang20170213; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; import java.util.Random; import static android.R.attr.width; import static com.bw.u.liangweihang20170213.R.id.text; public class MyView extends View{ private int x=202; private int y=317; private int radio=40; private Paint mPaint; private Paint ZPaint; private String suijishu; private String textContent; private int textColor; private android.graphics.Canvas canvas; private float height; private Random ran; private float width; public MyView(Context context) { this(context,null); } public MyView(Context context, AttributeSet attrs) { this(context, attrs,R.style.AppTheme); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); getConfig(context,attrs); } private void getConfig(Context context, AttributeSet attrs) { //得到数组 TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.MyView); //给颜色设置默认值 textColor = ta.getColor(R.styleable.MyView_textColor, Color.YELLOW); //回收容器 ta.recycle(); } //绘制圆的方法 protected void onDraw(Canvas canvas) { super.onDraw(canvas); //绘制画笔 ran = new Random(); mPaint = new Paint(); ZPaint = new Paint(); ZPaint.setColor(Color.CYAN); ZPaint.setStyle(Paint.Style.STROKE); //设置属性 mPaint.setStrokeWidth(30); mPaint.setStyle(Paint.Style.STROKE); mPaint.setAntiAlias(true); mPaint.setColor(textColor); //绘制第一个圆 canvas.drawCircle(x,y,radio,mPaint); //设置随机数 suijishu= String.valueOf(ran.nextInt(8999)+1000); width = mPaint.measureText(suijishu); //测量字体的位置 canvas.drawText(String.valueOf(suijishu),(getWidth()- width)/2,getHeight()/2,ZPaint); } public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: invalidate(); break; } return true; } }
//自定义属性
<declare-styleable name="MyView"> <attr name="textContent" format="string" /> <attr name="textColor" format="color" /> <attr name="textSize" format="dimension" /> </declare-styleable>