使用Android绘图技术绘制一个椭圆形,然后通过触摸事件让该椭圆形跟着手指移动

时间:2023-02-04 20:30:46

引言:在图形绘制中,控制一个图形(圆形,椭圆形,矩形,三角形)移动时,其实计算的都是该图形的中心点移动。在绘制过程中,首先计算出中心点,然后根据中心点的位置计算重图形的上下左右位置。我们假设图形左边为lx,图形右边为rx,图形上边为ty,图形下边为by,图形的中心点位置坐标为(cx,cy).手指触摸位置坐标为(x,y)

计算公式:

lx = x - cx;
rx = x + cx;
ty = y - cy;
by = y + cy;

下面是控制图形移动的具体代码:

 

GameView.java

package com.yw.mygame.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

public class GameView extends View{
    private Paint paint = null;
    private int x = 0;    
    private int y = 0;
    
    //椭圆形的left,right,top,buttom初始位置
    private float lx = 0.0f;
    private float rx = 50.0f;
    private float ty = 0.0f;
    private float by = 100.0f;
    
    /**
     * 椭圆形的中心点坐标(要始终保证中心点的这两个值不变)
     */
    private float cx = 25.0f;
    private float cy = 50.0f;
    public GameView(Context context) {
        super(context);
        this.setFocusable(true);//允许获取上层焦点
        paint = new Paint();
        paint.setColor(Color.GREEN);
//        new GameViewThread().start();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawLine(x, 0, x, 480, paint);
        RectF rectf = new RectF(lx, ty, rx, by);
        canvas.drawOval(rectf, paint);
    }
    
    /*class GameViewThread extends Thread{
        @Override
        public void run() {
            while(x <= 480){
                x+=5;
                postInvalidate();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        x = (int)event.getX();
        //触摸位置
        float x = event.getX();
        float y = event.getY();
        /*lx = cx - (rx-lx)/2;
        rx = cx + (rx-lx)/2;
        ty = cy - (by-ty)/2;
        by = cy + (by-ty)/2;*/
        //改变椭圆形位置
        lx = x - cx;
        rx = x + cx;
        ty = y - cy;
        by = y + cy;
        //对View进行重新绘制
        postInvalidate();
        return true;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return super.onKeyUp(keyCode, event);
    }
}

GameViewActivity.java

package com.yw.mygame;

import com.yw.mygame.view.GameView;

import android.app.Activity;
import android.os.Bundle;

public class GameViewActivity extends Activity{
    private GameView gameView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gameView = new GameView(this);
        setContentView(gameView);
    }

}