1

我正在使用 ImageView 创建画布并用手指触摸绘制元素。但问题是,首先画布只覆盖屏幕的一小部分来绘制或写东西,其次它会在我触摸的地方产生很远的线条或曲线。我有一个文本视图和线性布局的图像视图。请检查我的代码并帮助我。

DrawTestActivity.java:

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnTouchListener {
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Path path;
Paint paint;
float downx = 0, downy = 0, upx = 0, upy = 0;
float startX = 0;
float startY = 0;
float endX = 0;
float endY = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 imageView = (ImageView) this.findViewById(R.id.imageView1);

 Display display = getWindowManager().getDefaultDisplay();
 Point size = new Point();
 display.getSize(size);
 int width = size.x;
 int height = size.y;

 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
 canvas = new Canvas(bitmap);
 paint = new Paint();
 paint.setColor(Color.BLUE);
 paint.setAntiAlias(true);
 paint.setStrokeWidth(6f);
 paint.setStyle(Paint.Style.STROKE);
 paint.setStrokeJoin(Paint.Join.ROUND);
 imageView.setImageBitmap(bitmap);
 imageView.setOnTouchListener(this);
}

public boolean onTouch(View v, MotionEvent event) {
  int action = event.getAction();
  switch (action) {
  case MotionEvent.ACTION_DOWN:
   startX=event.getX();
   startY=event.getY();
   break;

  case MotionEvent.ACTION_MOVE:
   endX = event.getX();
   endY = event.getY();
   canvas.drawLine(startX,startY,endX,endY, paint);
   imageView.invalidate();
   startX=endX;
   startY=endY;
   break;

  case MotionEvent.ACTION_UP:
   break;
  case MotionEvent.ACTION_CANCEL:
   break;
  default:
   break;
}
 return true;
}
}
4

0 回答 0