自定義畫圓首先需要繼承View類并重寫三個構造方法public class Circle extends View { //聲明畫筆 Paint opaint; Paint tpaint; Paint thpaint; String text; int ny; int wy; public Circle(Context context) { super(context); } public Circle(Context context, AttributeSet attrs) { super(context, attrs); //在構造函數中來讀取attrs中的屬性 TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.Circle); text = ta.getString(R.styleable.Circle_text); //第一個參數相當屬性的id也就是屬性的名字,第二個參數為默認值,它是在自定義布局中配置的屬性不起作用時進行替換的 //顏色返回int類型的值 ny=ta.getColor(R.styleable.Circle_ny,Color.WHITE); wy=ta.getColor(R.styleable.Circle_wy,Color.YELLOW); //數值類型的要使用getDimension,返回float類型的值 float textsize=ta.getDimension(R.styleable.Circle_textsize,1);//記得此處要recycle(); ta.recycle(); } public Circle(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override PRotected void onDraw(Canvas canvas) { super.onDraw(canvas);//調用畫筆 Circl(canvas); }//重寫onTouchEvent方法點擊在不同位置,提示不同位置 @Override public boolean onTouchEvent(MotionEvent event) { int x; int y; switch (event.getAction()){ case MotionEvent.ACTION_DOWN: //得到點擊坐標 x= (int) event.getX(); y=(int) event.getY(); int x1=(x-getWidth()/2)*(x-getWidth()/2); int y1=(y-getHeight()/2)*(y-getHeight()/2); //判斷點擊位置是否在圓內 if (x1+y1<70*70){ Toast.makeText(getContext(),"小圓內",Toast.LENGTH_SHORT).show(); }else if (x1+y1<100*100&&x1+y1>70*70){ Toast.makeText(getContext(),"圓環內",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getContext(),"圓環外",Toast.LENGTH_SHORT).show(); } break; } return true; } //創建一個畫圓的方法 public void Circl(Canvas canvas){ //實例化第一只畫筆 opaint=new Paint(); opaint.setColor(ny); opaint.setAntiAlias(true); opaint.setStyle(Paint.Style.FILL); opaint.setStrokeWidth(1); //畫小圓 canvas.drawCircle(getWidth()/2,getHeight()/2,70,opaint); //實例化第二只畫筆 tpaint=new Paint(); tpaint.setColor(wy); tpaint.setAntiAlias(true); tpaint.setStyle(Paint.Style.STROKE); tpaint.setStrokeWidth(100); canvas.drawCircle(getWidth()/2,getHeight()/2,100,tpaint); //實例化第二只畫筆 thpaint=new Paint(); thpaint.setColor(Color.BLACK); thpaint.setAntiAlias(true); thpaint.setStyle(Paint.Style.STROKE); thpaint.setStrokeWidth(1); float yh=thpaint.measureText("圓環"); canvas.drawText("圓環",(getWidth()-yh)/2,getHeight()/2,thpaint); }} 在values文件下創建attrs.xml文件存放自定義屬性,代碼如下:<declare-styleable name="Circle"> <attr name="img" format="reference" /> <attr name="text" format="string"></attr> <attr name="ny" format="color"></attr> <attr name="wy" format="color"></attr> <attr name="textsize" format="dimension"></attr></declare-styleable> 在布局文件的xml中配置自定義屬性的具體內容,如下:<com.bwei.zhaoyangyang20170206.Circle android:id="@+id/cl" android:background="#ff00ff00" android:layout_width="wrap_content" android:layout_height="wrap_content" app:ny="#ff00ff" app:wy="#ffff00" app:textsize="10dp" />
新聞熱點
疑難解答