【发布时间】:2015-05-15 10:51:46
【问题描述】:
我对 Android 还是很陌生,我真的很难理解我的应用程序中发生了什么。 我正在尝试构建一个小游戏,其中一个圆圈出现在屏幕上,随机位置,一旦用户点击它就会消失。然后一个新的圆圈出现在另一个位置。
问题是对比用户点击的坐标,和圆心的坐标,这些好像完全不一样……
问题似乎出在圆坐标上,因为如果我试图将其位置强制到视图的中心,它会出现在一个完全错误的位置,即视图的右下角。
我做错了什么?
这是在视图中绘制圆圈的函数的代码(与其父级一样大)。
public void drawDots(){
Paint paint = new Paint();
paint.setColor(Color.MAGENTA);
Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
View ll = (View) findViewById(R.id.circle);
ll.setBackground(new BitmapDrawable(bg));
centerX = rand.nextInt(ll.getWidth());
centerY = rand.nextInt(ll.getHeight());
Canvas canvas = new Canvas(bg);
canvas.drawCircle(centerX, centerY, radius, paint);
Log.i("Point center X :" + centerX, " Y " + centerY);
ll.setOnTouchListener(new View.OnTouchListener() {
int x = 0, y = 0;
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
x = (int) event.getX();
y = (int) event.getY();
Log.i("CLICK X: " + x, "click Y: " + y);
if((x < (centerX + radius) && x > (centerX - radius))) && ((y > centerY + radius) && (y < centerY - radius)) ){
Log.i("x ok: " + x + " y ok: " + y, "Counter: " + counter);
drawDots();
}else{
Log.i("x NOT ok " + x, " Circle area between: " + (centerX-radius) + " e " + (centerX + radius));
Log.i("Y NOT ok " + y, " Circle area between: " + (centerY-radius) + " e " + (centerY + radius));
}
}
return true;
}
});
}
这就是布局。启动计时器需要 textview 和按钮,但一旦用户单击开始按钮,它们就会从布局中删除。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:id="@+id/timerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="37dp"
android:textSize="40sp"
android:textColor="#ffffff"
android:text="@string/timerVal" />
<Button
android:id="@+id/startButton"
android:layout_width="90dp"
android:layout_height="45dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="38dp"
android:text="@string/startButtonLabel" />
<View android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/circle"/>
抱歉我的解释不好,但我什至不知道问题出在哪里。
编辑我尝试了这个解决方案,它实际上似乎改善了这种情况,但如果我只考虑 x 轴,对于 y 轴有任何对应关系,但这样看来坐标的点击完全超出范围...Circle drawn on canvas doesn't match the screen
即使我实际上不明白为什么需要它
【问题讨论】:
-
你也可以发布一个布局吗?
标签: java android canvas drawing