// xml的部分 自定义控件之后要在xml中引用
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.bw.u.day_03duodianchukong.MainActivity"> <com.bw.u.day_03duodianchukong.MyView android:layout_width="match_parent" android:layout_height="match_parent" /></RelativeLayout> 继承button的部分package com.bw.u.day_03duodianchukong;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.util.Log;import android.view.MotionEvent;import android.widget.Button;import android.widget.Toast;public class MyView extends Button{ PRivate float x=202; private float y=317; private Paint mpaint; private int width; private float radius=5; private float x_s_old; private float y_s_old; private float x_s_new; private float y_s_new; private float old=0; private float ne1=0; private float round=50; 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); } protected void onDraw(Canvas canvas) { super.onDraw(canvas); width = getWidth(); int radio = 60; //创建画笔 mpaint = new Paint(); mpaint.setAntiAlias(true); mpaint.setStrokeWidth(5);//绘制圆的宽度 mpaint.setStyle(Paint.Style.FILL); mpaint.setColor(Color.RED); //开始画圆 canvas.drawCircle(x,y,radio,mpaint); } public boolean onTouchEvent(MotionEvent event) { //多点触控 switch (event.getAction()&event.ACTION_MASK){ case MotionEvent.ACTION_POINTER_DOWN: x_s_old=event.getX(0)-event.getX(1); y_s_old=event.getY(0)-event.getY(1); old=(float) Math.sqrt(x_s_old*x_s_old+y_s_old*y_s_old); break; case MotionEvent.ACTION_MOVE: //抛异常 要不然会报错 try { x_s_new=event.getX(event.getPointerId(0))-event.getX(event.getPointerId(1)); y_s_new=event.getY(event.getPointerId(0))-event.getY(event.getPointerId(1)); ne1=(float) Math.sqrt(x_s_new*x_s_new+y_s_new*y_s_new); }catch (IllegalArgumentException e){ e.printStackTrace(); } if(ne1>old){ float side=round+3; round=side; round=side; Log.i("aaa", round+""); }else if(ne1<old){ float side=round-3; round=side; } invalidate(); break; case MotionEvent.ACTION_UP: break; } //单点触控 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Toast.makeText(getContext(),"点击",Toast.LENGTH_SHORT).show(); break; case MotionEvent.ACTION_MOVE: float x_t=event.getX(); float y_t=event.getY(); float t=(x_t-x)*(x_t-x)+(y_t-y)*(y_t-y); float sqrt = (float) Math.sqrt(t); if(sqrt<=50){ x=event.getX(); y=event.getY(); invalidate(); } break; case MotionEvent.ACTION_UP: break; } return true; }}
新闻热点
疑难解答