android中没有油漆

时间:2012-11-23 11:04:45

标签: android canvas paint

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

我在函数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;
  } 
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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