除了使用触摸,我想画任何东西。我按照this教程。但是我的绘图并不是从我触摸屏幕的那一刻开始的。
我也试过包括状态栏和标题栏的高度,但它没有用。
我的活动代码:
public class MainActivity extends Activity implements OnTouchListener {
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
float downx = 0, downy = 0, upx = 0, upy = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) this.findViewById(R.id.imageView1);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
bitmap = Bitmap.createBitmap(metrics.widthPixels, metrics.heightPixels,
Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(this);
}
public int getStatusBarHeight() {
Rect r = new Rect();
Window w = getWindow();
w.getDecorView().getWindowVisibleDisplayFrame(r);
return r.top;
}
public int getTitleBarHeight() {
int viewTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT)
.getTop();
return (viewTop - getStatusBarHeight());
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY() - getStatusBarHeight() - getTitleBarHeight();
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY()+ getStatusBarHeight() + getTitleBarHeight();
canvas.drawLine(downx, downy, upx, upy, paint);
imageView.invalidate();
downx = upx;
downy = upy;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:0)
yourcode
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
bitmap = Bitmap.createBitmap(metrics.widthPixels, metrics.heightPixels,Bitmap.Config.ARGB_8888);
按照link所示进行更改并检查
Display currentDisplay = getWindowManager().getDefaultDisplay();
float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
bitmap = Bitmap.createBitmap((int) dw, (int) dh,Bitmap.Config.ARGB_8888);