代码如下:
[code="java"]
package com.android.SimpleDemo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class TouchMoveView extends View {
private float x=0;
private float y=0;
private RectF rect=new RectF();
public TouchMoveView(Context context) {
super(context);
rect.set(0, 0, 100, 100);
}
public TouchMoveView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TouchMoveView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected void onDraw(Canvas canvas) {
Paint mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setAntiAlias(true);
canvas.drawRect(rect.left+offsetSize.x,
rect.top+offsetSize.y,
rect.left+offsetSize.x+rect.width(),
rect.top+offsetSize.y+rect.height(),
mPaint);
mPaint.setColor(Color.WHITE);
canvas.drawText("x="+x+" y="+y, x, y, mPaint);
super.onDraw(canvas);
}
private PointF downPoint=new PointF();
private PointF currPoint=new PointF();
private PointF offsetSize=new PointF();
private boolean moving=false;
public boolean onTouchEvent(MotionEvent event){
x = event.getX();
y = event.getY();
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
if(!rect.contains(x, y))
return false;
moving=true;
downPoint.set(x, y);
return true;
case MotionEvent.ACTION_UP:
moving=false;
rect.offset(offsetSize.x, offsetSize.y);
this.invalidate();
offsetSize.set(0, 0);
return true;
case MotionEvent.ACTION_MOVE:
if(moving){
currPoint.set(x, y);
offsetSize.x=currPoint.x-downPoint.x;
offsetSize.y=currPoint.y-downPoint.y;
}
this.invalidate();
return true;
}
return false;
}
}
[/code]
[img]http://dl.iteye.com/upload/attachment/200638/5b7184c9-407b-3661-8215-de4bfb851df0.png[/img]
程序是运行显示100*100代正方形,点击正方形并移动,然而鼠标移动过程中,图形并未紧跟着移动。
是不是鼠标移动触发的消息太多,以至于消息队列不能及时处于绘图事件?还是java性能上的问题或是手机模似器的问题?
有没有什么解决方法?
谢谢!