2

我正在为签名编写迷你应用程序,用户使用手指进行绘画。

我画了功能onPaint,但什么也没有。我不明白,我调试了但我没有修复它。我明白了,如果我在函数onCreate中绘制就可以了。

我想在onPaint上画画。

public class Main extends Activity{
  ImageView drawingImageView;
  float downx = 0;
  float downy = 0;
  float upx = 0;
  float upy = 0;
  private Bitmap bitmap;
  private Canvas canvas;
  private Path mPath;
  private Paint mBitmapPaint;
  private Paint mPaint;

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

    drawingImageView = (ImageView) this.findViewById(R.id.imageView1);
    bitmap = Bitmap.createBitmap((int) getWindowManager()
        .getDefaultDisplay().getWidth(), (int) getWindowManager()
        .getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
    canvas = new Canvas(bitmap);
    drawingImageView.setImageBitmap(bitmap);

    mBitmapPaint = new Paint(Paint.DITHER_FLAG);

    mPath = new Path(); 

    mPaint = new Paint();
    mPaint.setColor(Color.GREEN);
    mPaint.setTextSize(20);
    mPaint.setTypeface(Typeface.DEFAULT);

    canvas.drawLine(0, 0, 200, 200, mPaint);
  }


  protected void onDraw(Canvas canvas) {
    canvas.drawColor(0xFFAAAAAA);
    canvas.drawBitmap(bitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mPath, mPaint);
    canvas.drawLine(0, 0, 100, 100, mPaint);
  }
  private float mX, mY;
  private static final float TOUCH_TOLERANCE = 4;
  private void touch_start(float x, float y) {
    mPath.reset();
    mPath.moveTo(x, y);
    mX = x;
    mY = y;
  }
  private void touch_move(float x, float y) {
    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
      mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
      mX = x;
      mY = y;
    }
  }
  private void touch_up() {
    mPath.lineTo(mX, mY);
    // commit the path to our offscreen
    canvas.drawPath(mPath, mPaint);
    // kill this so we don't double draw
    mPath.reset();
  }
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
      touch_start(x, y);
      onDraw(canvas);
      break;
    case MotionEvent.ACTION_MOVE:
      touch_move(x, y);
      onDraw(canvas);
      break;
    case MotionEvent.ACTION_UP:
      touch_up();
      onDraw(canvas);
      break;
    }
    return true;
  } 
}
4

2 回答 2

1

canvas.restore();在所有绘图操作后调用。

于 2012-11-23T11:13:10.907 回答
0

除了糟糕的代码格式之外:您不能在 onTouch 方法中使用自己创建的画布调用 onDraw()。要获得有关 2D 绘图的基本感觉,请查看我的教程系列

于 2012-11-23T11:09:06.523 回答