自定义View放大缩小


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        setContentView(new Mainview(this));

    }
}
 
  
public class Mainview extends View {
    private float cx = 300;
    private float cy = 300;
    private Paint p;
    private double sqrt,sqr,sq=100;
    public Mainview(Context context) {
        super(context);
    }

    public Mainview(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public Mainview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        //创建画笔
        p = new Paint();
        //设置画笔的颜色
        p.setColor(Color.GREEN);
        //绘制一个球
        canvas.drawCircle(cx, cy, (float) sq, p);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_DOWN:
                if(event.getPointerCount()>1){
                    sqr = Math.sqrt((Math.pow(event.getX(0) - event.getX(1), 2) + Math.pow(event.getY(0) - event.getY(1), 2)));
                }
                break;
            case MotionEvent.ACTION_MOVE:
                float x1 = event.getX();
                float y1 = event.getY();
                double sqrt = Math.sqrt((Math.pow(x1 - cx, 2) + Math.pow(y1 - cy, 2)));
                if (sqrt < 100) {
                    cx=x1;
                    cy=y1;
                    invalidate();
                }
                if(event.getPointerCount()>1){
                    sqrt = Math.sqrt((Math.pow(event.getX(0) - event.getX(1), 2) + Math.pow(event.getY(0) - event.getY(1), 2)));
                    if(sqrt<sqr){
                        //sqrt=sqr;
                        sqr=sqrt;
                        sq-=3;
                        invalidate();
                    }else{
                        sqr=sqrt;
                        sq+=3;
                        invalidate();
                    }
                }
                break;
        }
        return true;
    }
}
 
  
 
  
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

你可能感兴趣的:(自定义View放大缩小)