我正在尝试绘制一个我触摸的圆圈,所以我使用OnTouchListener来获取x,y坐标。 但是当我在模拟器上运行代码时,我没有在单击的位置绘制圆圈。
public class MainActivity extends AppCompatActivity {
Canvas canvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//------------------
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;//480
int screenHeight = displaymetrics.heightPixels;//1920
Bitmap bg = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bg);
RelativeLayout ll = (RelativeLayout) findViewById(R.id.RelativeLayoutCells);
ll.setBackgroundDrawable(new BitmapDrawable(bg));
ll.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
float xf = event.getRawX();
float yf = event.getRawY();
Log.d("=", String.valueOf(x) + " " + String.valueOf(xf));
Paint fillpaint= new Paint();;
fillpaint.setColor(Color.RED);
fillpaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(xf, yf, 5, fillpaint);
canvas.drawCircle(x, y, 15, fillpaint);
}
Button button = (Button) findViewById(R.id.button);
button.setText("ghj");
return false;
}
});
}
}
答案 0 :(得分:0)
您不应该使用event.getRawX()
。返回的值是完全原始的,不会根据您的视图进行调整。如果未缩放画布,请改用event.getX()
。它因为它的回归而有所不同。 getX返回x调整为自定义视图,但getRawX基于导致不准确的屏幕。