如何在android中使用onTouch进行圆圈移动

时间:2015-08-08 12:26:18

标签: android geometry ontouchevent

我是编程新手。我试图通过使用OnTouchListener移动一个圆圈,但是我不知道如何在onTouch事件中调用它,因为我有一个带有x和y的圆的类和一个名为Drawing(d)的类来绘制它在画布上。我突出了我发现有问题的线条。谢谢。

``

public class FirstPicture extends Activity implements OnTouchListener {
    Drawing d;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            d=new Drawing(this);

            setContentView(d);
            d.setOnTouchListener(this);
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            **d.c1.getX() = event.getX();
            d.c1.getY()= event.getY();**
            d.invalidate();


            return true;
        }
    }


public class Drawing  extends View{
    Context ctx;
    Circle c1;

    public Drawing(Context context) {
            super(context);
            this.ctx = context;
            c1 = new Circle (165, 350, 33);


        }
    protected void onDraw (android.graphics.Canvas canvas){
        Paint p = new Paint();
        Paint p1 = new Paint ();
        Paint p2 = new Paint ();
        Paint p3= new Paint();
        Paint p4 = new Paint();

        p2.setColor(Color.WHITE);
        p.setColor(Color.GREEN);
        p3.setColor(Color.RED);
        p1.setColor(Color.BLACK);
        p4.setColor(Color.BLUE);
        p1.setStyle(Style.FILL);
        p1.setStyle(Style.FILL_AND_STROKE);
        p1.setTextSize(19);

        canvas.drawCircle(c1.getX(), c1.getY(), c1.getR(), p4);
        canvas.drawText("100", c1.getX()-15, c1.getY()+5, p1);

    }

    }

    public class Circle {
    private float x;
    private float y;
    private float r;
    public Circle(float x, float y, float r) {
        super();
        this.x = x;
        this.y = y;
        this.r = r;
    }
    public float getX() {
        return x;
    }
    public void setX(float x) {
        this.x = x;
    }
    public float getY() {
        return y;
    }
    public void setY(float y) {
        this.y = y;
    }
    public float getR() {
        return r;
    }
    public void setR(float r) {
        this.r = r;
    }

    }

1 个答案:

答案 0 :(得分:0)

您正在尝试分配到getter:

d.c1.getX() = event.getX()

如何在Drawing视图上公开更新方法。

private int circleCenterX;
private int circleCenterY;

public void update(int x, int y) {
    this.circleCenterX = x;
    this.circleCenterY = y;
}

@Override
protected void draw(Canvas canvas) {
    canvas.drawCircle(circleCenterX, circleCenterY, c1.getR(), p4);
    canvas.drawText("100", c1.getX() - 15, c1.getY() + 5, p1);
}

然后你的onTouch成为:

@Override
public boolean onTouch(View v, MotionEvent event) {
    d.update(event.getX(), event.getY());
    return true;
}
  • 在draw方法之外实例化所有Paint对象 - 可能在您实例化圆圈的构造函数中。实例化对象是一项相对繁重的操作,您不希望在draw()发生时执行此操作,尤其是当它发生60x秒时。
  • 我确定自动调用视图上的draw()方法,因此不需要使视图无效(但即使你这样做,也不会重新绘制视图直到下一帧 - 取这个子弹点和括号内的这一点有一点点盐!)