我想要做一個簡單的圖形用戶界面交互 - 觸摸屏幕,並有一個紅色的球從它以前的位置移動。一切都很好,只是我的球出現在我想要的偏移處。偏移量與我繪製原始球的位置直接相關。就好像球視圖包含作爲其大小一部分的偏移量。 例如,如果我在X = 100處繪製原稿,Y = 100的半徑爲25,則後來必須從我的每個getX和getY返回值中減去100,以使其放置在適當的位置。我相信這是不正常的,但一直未能發現我的問題。有人可以幫忙嗎?代碼是onDraw操作不會把圓圈放在我期望的位置
public LinearLayout my_canvas;
public Ball ball1;
public class Ball extends View {
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Ball(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
LinearLayout.LayoutParams tlp =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
this.setLayoutParams(tlp);
this.x = x;
this.y = y;
this.r = r;
Log.v("BookOne", "ball constructor at "+x+","+y);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
my_canvas.invalidate();
}
}
是我的主要應用程序。其次
my_canvas = (LinearLayout) findViewById(R.id.my_canvas);
my_canvas.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
Log.v("BookOne", "Entered onTouch for canvas");
float x = e.getX();
float y = e.getY();
Log.v("BookOne", "set coordinates");
ball1.setX(x);
ball1.setY(y);
ball1.invalidate();
//my_canvas.invalidate();
Log.v("BookOne", "get ranges");
int r = v.getRight();
int l = v.getLeft();
int t = v.getTop();
int b = v.getBottom();
int w = v.getWidth();
int h = v.getHeight();
Log.v("BookOne", "Ball moving to "+x+","+y);
log_view_dimensions("ball1 dimensions", ball1);
log_view_dimensions("View v dimensions", v);
log_view_dimensions("my_canvas dimensions", my_canvas);
Log.v("BookOne", "about to return FALSE");
return(false);
}
});
ball1 = new Ball(my_canvas.getContext(), 100, 100, 25);
my_canvas.addView(ball1);
Log.v("BookOne", "ball1 added");
的X和Y值我從的getX和獲得的getY出現正確,但球正在重繪100個像素的路程。
僅供參考,這裏是從logcat中轉儲:
07-26 20:54:43.830:VERBOSE/BookOne(5463):進入onTouch帆布 07-26 20:54:43.830:VERBOSE/BookOne( 5463):設置座標 07-26 20:54:43.830:VERBOSE/BookOne(5463):取得範圍 07-26 20:54:43.830:VERBOSE/BookOne(5463):球移動到337.0,262.5 07- 26 20:54:43.830:VERBOSE/BookOne(5463):ball1維度l = 0; R = 800; T = 0; b = 536 07-26 20:54:43.830:VERBOSE/BookOne(5463):ball1 dimensions w = 800; h = 536 07-26 20:54:43.830:VERBOSE/BookOne(5463):查看v維度l = 0; R = 800; T = 584; b = 1120 07-26 20:54:43.830:VERBOSE/BookOne(5463):View v dimensions w = 800; h = 536 07-26 20:54:43.830:VERBOSE/BookOne(5463):my_canvas維度l = 0; R = 800; T = 584; b = 1120 07-26 20:54:43.830:VERBOSE/BookOne(5463):my_canvas尺寸w = 800; h = 536 07-26 20:54:43.830:VERBOSE/BookOne(5463):即將返回FALSE
注意ball1上的尺寸。什麼影響?
非常感謝您的任何幫助。
邁克