0

有人知道如何清除位图和画布吗?我认为 somewere 是错误的或不完整的代码。例如,在 public void forceRedraw() 的 FirstActivity.java 上,我收到一条消息以在 invalidate() 上创建方法。如果您需要其他课程,请告诉我。我真的不知道我的错误在哪里。我正在使用以下代码。它有点大,但希望能理解它。

这是我的 FirstActivity.java

public class FirstActivity extends Activity implements ColorPickerDialog.OnColorChangedListener {

Paint mPaint;
private Paint paint = new Paint();
private Path path = new Path();
CanvasView myView;

static LinearLayout ll;
ImageView imageViewLine;
ImageView imageViewRectangle;
private ImageView imageViewErase;
private ImageView imageViewFreehand;
private ImageView imageViewUndo;
private ImageView imageViewRedo;

private final int CONTEXT_MENU_LINES_ID = 1;
private final int CONTEXT_MENU_SHAPES_ID = 2;
private final int CONTEXT_MENU_COLOR_ID = 3;

private IconContextMenu iconContextMenuLine = null;
private IconContextMenu iconContextMenuShapes = null;
private IconContextMenu iconContextMenuColors = null;

private final int MENU_ITEM_1_ACTION = 1;
private final int MENU_ITEM_2_ACTION = 2;
private final int MENU_ITEM_3_ACTION = 3;
private final int MENU_ITEM_4_ACTION = 4;
private final int MENU_ITEM_5_ACTION = 5;
private final int MENU_ITEM_6_ACTION = 6;
private final int MENU_ITEM_7_ACTION = 7;
private final int MENU_ITEM_8_ACTION = 8;

private ImageView imageViewText;

private ImageView imageViewColor;

private File folderAppointment;

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

    initContextMenus();

    myView = (CanvasView)this.findViewById(R.id.canvasView);

    ll = (LinearLayout) this.findViewById(R.id.linearLayout2);
    ll.setVisibility(LinearLayout.GONE);

    imageViewLine = (ImageView)this.findViewById(R.id.imageViewLine);
    imageViewLine.setOnClickListener(new OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Line tool clicked", Toast.LENGTH_SHORT).show();
            myView.setMode(1); //draw line
            myView.setOnTouchListener(myView.drawLineListener);
            showDialog(CONTEXT_MENU_LINES_ID,null);
        }
    });

    imageViewRectangle = (ImageView)this.findViewById(R.id.imageViewSquare);
    imageViewRectangle.setOnTouchListener(new OnTouchListener() {

        @SuppressWarnings("deprecation")
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN)
            {
                Toast.makeText(getApplicationContext(), "Rectangle tool clicked", Toast.LENGTH_SHORT).show();
                myView.setMode(5); //draw rectangle
                showDialog(CONTEXT_MENU_SHAPES_ID,null);
                return true;
            }
            return false;
        }
    });

    imageViewErase = (ImageView)this.findViewById(R.id.imageViewEraser);
    imageViewErase.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Eraser tool clicked", Toast.LENGTH_SHORT).show();
            myView.setMode(6); //eraser

        }
    });

    imageViewFreehand = (ImageView)this.findViewById(R.id.imageViewSquiggle);
    imageViewFreehand.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Squiggle tool clicked", Toast.LENGTH_SHORT).show();
            myView.setMode(7);//free hand draw

        }
    });

    imageViewUndo = (ImageView)this.findViewById(R.id.imageViewUndo);
    imageViewUndo.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Undo tool clicked", Toast.LENGTH_SHORT).show();
            myView.setMode(9);//undo

        }
    });

    imageViewRedo = (ImageView)this.findViewById(R.id.imageViewRedo);
    imageViewRedo.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Redo tool clicked", Toast.LENGTH_SHORT).show();
            myView.setMode(10);//redo

        }
    });

    imageViewText = (ImageView)this.findViewById(R.id.imageViewText);
    imageViewText.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Text tool clicked", Toast.LENGTH_SHORT).show();
            myView.setMode(8);//text input
        }
    });

    imageViewColor = (ImageView)this.findViewById(R.id.imageViewColor);
    imageViewColor.setOnClickListener(new OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Select color", Toast.LENGTH_SHORT).show();
            //myView.setMode(5); //draw rectangle
            showDialog(CONTEXT_MENU_COLOR_ID,null);


        }
    });

 }

@SuppressWarnings("deprecation") // to be optimized using switch instead of nested if-s
protected Dialog onCreateDialog(int id) {
    if (id == CONTEXT_MENU_LINES_ID) {
        return iconContextMenuLine.createMenu("Lines");
    }
    else if(id == CONTEXT_MENU_SHAPES_ID){
        return iconContextMenuShapes.createMenu("Shapes");
    }
    else if(id == CONTEXT_MENU_COLOR_ID){
        return iconContextMenuColors.createMenu("Choose color");
    }
    return super.onCreateDialog(id);
}

public  void initContextMenus(){
    Resources res = getResources();
    //init icon context menu
    iconContextMenuLine = new IconContextMenu(this, CONTEXT_MENU_LINES_ID);
    iconContextMenuLine.addItem(res, "", R.drawable.line, MENU_ITEM_2_ACTION);
    iconContextMenuLine.addItem(res, "", R.drawable.linie_taiata, MENU_ITEM_4_ACTION);

    iconContextMenuLine.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
        public void onClick(int menuId) {
            switch(menuId) {

            case MENU_ITEM_2_ACTION:
                Toast.makeText(getApplicationContext(), "You've clicked normal line", Toast.LENGTH_SHORT).show();
                myView.setNormalLine();
                myView.setMode(1); //draw line
                break;
            case MENU_ITEM_4_ACTION:
                Toast.makeText(getApplicationContext(), "You've clicked dashed line", Toast.LENGTH_SHORT).show();
                myView.setDashLine();
                myView.setMode(2);//draw  dashed line
                break;

            }
        }
    });

    iconContextMenuShapes = new IconContextMenu(this, CONTEXT_MENU_SHAPES_ID);
    iconContextMenuShapes.addItem(res, "", R.drawable.cerc,MENU_ITEM_1_ACTION);
    iconContextMenuShapes.addItem(res, "",R.drawable.square, MENU_ITEM_2_ACTION);

    iconContextMenuShapes.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
        public void onClick(int menuId) {

            switch(menuId) {

            case MENU_ITEM_1_ACTION:
                Toast.makeText(getApplicationContext(), "You've clicked circle", Toast.LENGTH_SHORT).show();
                myView.setMode(4); //draw circle
                break;
            case MENU_ITEM_2_ACTION:
                Toast.makeText(getApplicationContext(), "You've clicked rectangle", Toast.LENGTH_SHORT).show();
                myView.setMode(5); //draw  rectangle
                break;

            }
        }
    });

    iconContextMenuColors = new IconContextMenu(this, CONTEXT_MENU_SHAPES_ID);
    iconContextMenuColors.addItem(res, "", R.drawable.red,MENU_ITEM_1_ACTION);
    iconContextMenuColors.addItem(res, "",R.drawable.green, MENU_ITEM_2_ACTION);
    iconContextMenuColors.addItem(res, "",R.drawable.blue, MENU_ITEM_3_ACTION);
    iconContextMenuColors.addItem(res, "", R.drawable.magenta,MENU_ITEM_4_ACTION);
    iconContextMenuColors.addItem(res, "",R.drawable.yellow, MENU_ITEM_5_ACTION);
    iconContextMenuColors.addItem(res, "",R.drawable.white, MENU_ITEM_6_ACTION);
    iconContextMenuColors.addItem(res, "", R.drawable.black,MENU_ITEM_7_ACTION);
    iconContextMenuColors.addItem(res, "", R.drawable.black,MENU_ITEM_8_ACTION);

    iconContextMenuColors.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
        public void onClick(int menuId) {

            switch(menuId) {

            case MENU_ITEM_1_ACTION:
                Toast.makeText(getApplicationContext(), "Red", Toast.LENGTH_SHORT).show();
                myView.changeColor(Color.RED);

                break;
            case MENU_ITEM_2_ACTION:
                Toast.makeText(getApplicationContext(), "Green", Toast.LENGTH_SHORT).show();
                myView.changeColor(Color.GREEN);
                break;

            case MENU_ITEM_3_ACTION:
                Toast.makeText(getApplicationContext(), "Blue", Toast.LENGTH_SHORT).show();
                myView.changeColor(Color.BLUE);

                break;
            case MENU_ITEM_4_ACTION:
                Toast.makeText(getApplicationContext(), "Magenta", Toast.LENGTH_SHORT).show();
                myView.changeColor(Color.MAGENTA);

                break;
            case MENU_ITEM_5_ACTION:
                Toast.makeText(getApplicationContext(), "Yellow", Toast.LENGTH_SHORT).show();
                myView.changeColor(Color.YELLOW);

                break;
            case MENU_ITEM_6_ACTION:
                Toast.makeText(getApplicationContext(), "White", Toast.LENGTH_SHORT).show();
                myView.changeColor(Color.WHITE);

                break;
            case MENU_ITEM_7_ACTION:
                Toast.makeText(getApplicationContext(), "Black", Toast.LENGTH_SHORT).show();
                myView.changeColor(Color.BLACK);

                break;
            case MENU_ITEM_8_ACTION:
                Toast.makeText(getApplicationContext(), "Blue", Toast.LENGTH_SHORT).show();
                myView.changeColor(Color.BLUE);

                break;

            }
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.first_activity, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item){
     switch (item.getItemId()) {
     case R.id.tools:
        ll.setVisibility(LinearLayout.VISIBLE);
        return true;
     case R.id.import_pics:
         getPhotos();
         return true;
     case R.id.save:
        toJPEGFile();
         return true;
     case R.id.trash:
        clearPoints();
         return true;
     }
    return false;

}


public void clearPoints () {
        forceRedraw();
}

    public void forceRedraw() {
        invalidate();
    }

private void toJPEGFile() {
    // TODO Auto-generated method stub
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           Bitmap finalBitmap = CanvasView.bitmap;
           finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

    } catch (Exception e) {
           e.printStackTrace();
    }
}


public void getPhotos(){
    Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, 1);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri chosenImageUri = data.getData();
        Toast.makeText(getApplicationContext(), "Photo background added!", Toast.LENGTH_SHORT).show();      

        Bitmap mBitmap = null;
        try {
            mBitmap = Media.getBitmap(this.getContentResolver(), chosenImageUri);
            if(mBitmap.isMutable())
                Toast.makeText(getApplicationContext(), "is mutable", Toast.LENGTH_SHORT).show();
            //cView = new MyCustomView(getApplicationContext(), null);
            myView.setImage(mBitmap);
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        }
}

public void colorChanged(int color) {
    mPaint.setColor(color);

}
}

在这里你有 CanvasView.java

public class CanvasView extends View{

private ArrayList<Path> undonePaths = new ArrayList<Path>(); 
private ArrayList<Path> paths = new ArrayList<Path>();
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH/2;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
Paint erasePaint = new Paint();
Paint paint = new Paint();
Path path = new Path();

float lastTouchX,lastTouchY;

AlertDialog.Builder alert;

RectF ovalRectangle = new RectF();
RectF dirtyRect = new RectF();

MyRectangle myRectangle;
MyOval myOval;
MyCircle myCircle;
MyFreehand myFreehand; 
MyLine myLine;
MyEraser myEraser;

List<MyEraser> eraserList = new ArrayList<MyEraser>();
List<MyLine> lineList = new ArrayList<MyLine>();
List<MyFreehand> freehandList  = new ArrayList<MyFreehand>();
List<MyCircle> circleList = new ArrayList<MyCircle>();
List<MyOval> ovalList = new ArrayList<MyOval>();
List<MyRectangle> rectangleList = new ArrayList<MyRectangle>();



public boolean dashedLine = false;
public DashPathEffect dashEffect = new DashPathEffect(new float[]{20,30}, 0);
private Paint mBitmapPaint;
private Bitmap mBitmap; 

public String textValue;

public CanvasView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setBackgroundColor(Color.WHITE);


    if (android.os.Build.VERSION.SDK_INT >= 11) 
    {
        turnOffHardwareAcc();
    }


    erasePaint.setColor(Color.TRANSPARENT);
    //erasePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

    erasePaint.setAntiAlias(true);
    erasePaint.setStyle(Paint.Style.STROKE);
    erasePaint.setStrokeJoin(Paint.Join.ROUND);
    erasePaint.setStrokeWidth(5f);

    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.STROKE);

    paint.setAntiAlias(true);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeWidth(STROKE_WIDTH);
    paint.setTextSize(72);

    setMode(7);//default = 7 - free hand;

    mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);

    /* input dialog*/

     //setInputDialog();

}
EditText input;
public void setInputDialog(){

    alert = new AlertDialog.Builder(getContext());
    alert.setTitle("Title");
    alert.setMessage("Write text");

    // Set an EditText view to get user input 
    input = new EditText(getContext());
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
         textValue= input.getText().toString();
         Toast.makeText(getContext(), textValue, Toast.LENGTH_SHORT).show();
      // Do something with value!
      }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        // Canceled.
      }
    });

    //alert.show();

}

private void touch_start(float x, float y) {
    undonePaths.clear();
    path.reset();
    path.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) {
        path.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
        mX = x;
        mY = y;
    }
}
private void touch_up() {
    path.lineTo(mX, mY);
    Canvas mCanvas = null;
    // commit the path to our offscreen
    mCanvas.drawPath(path, paint);
    // kill this so we don't double draw
    paths.add(path);
    path = new Path();            

}

public void Undo () { 
    if (paths.size()>0) { 
       undonePaths.add(paths.remove(paths.size()-1));
       invalidate();
     }
    else
    {

    }
}

public void Redo (){
   if (undonePaths.size()>0) { 
       paths.add(undonePaths.remove(undonePaths.size()-1));
       invalidate();
   } 
   else
   {

   }
}

public void setDashLine(){

    dashedLine = true;
    paint = new Paint();
    paint.setPathEffect(dashEffect);
    paint.setStyle(Paint.Style.STROKE);
    paint.setAntiAlias(true);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeWidth(STROKE_WIDTH);
}

public void setNormalLine(){
    //paint.setColor(Color.BLACK);
    dashedLine = false;

    paint.setPathEffect(null);
    paint.setStyle(Paint.Style.STROKE);
    paint.setPathEffect(null);
    paint.setAntiAlias(true);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeWidth(STROKE_WIDTH);
}

@TargetApi(11)
public void turnOffHardwareAcc() // to enable dashed lines
{

    this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

//public void setPaint(int color,)

@TargetApi(11)
protected void onDraw(Canvas canvas) {
    paint.setPathEffect(null);


    if(bitmap!=null){

        canvas.drawBitmap(bitmap, 0, 0, paint);
         for(MyCircle circle:circleList){// draw circles

             myCanvas.drawCircle(getCircleMidPointX(circle.firstX, circle.lastX),getCircleMidPointY(circle.firstY, circle.lastY),circle.radius,myPaint);
         }

    }


    for(MyLine line:lineList){ //draw lines
         if(dashedLine)
             line.paint.setPathEffect(dashEffect);
         else
             line.paint.setPathEffect(null);
            canvas.drawLine(line.xStart, line.yStart, line.xEnd, line.yEnd, line.paint);
      }

     for(MyCircle circle:circleList){// draw circles

         canvas.drawCircle(getCircleMidPointX(circle.firstX, circle.lastX),getCircleMidPointY(circle.firstY, circle.lastY),circle.radius,paint);
     }

     for(MyOval oval:ovalList){
         oval.paint.setPathEffect(null);

           ovalRectangle.set(oval.getX1(),oval.getY1(),oval.getX2(),oval.getY2());
           canvas.drawOval(ovalRectangle, oval.paint);
     }

     for(MyRectangle rectangle:rectangleList){
         rectangle.paint.setPathEffect(null);

           canvas.drawRect(rectangle.getX1(),rectangle.getY1(),rectangle.getX2(),rectangle.getY2(),rectangle.paint);
     }  

     for(MyEraser e:eraserList){
            canvas.drawPath(e.p,erasePaint);
            invalidate();
     }
     if(textValue!= null)
         canvas.drawText(textValue, xStart, yStart, paint);
     canvas.drawPath(path, paint);
     //path.reset();

}

public boolean onTouch(View arg0, MotionEvent event) {
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
    }
    return true;
}

final OnTouchListener drawLineListener = new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {

        FirstActivity.ll.setVisibility(LinearLayout.GONE);

        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
              myLine = new MyLine();
              myLine.xStart = event.getX();
              myLine.yStart = event.getY();

            return true;

          case MotionEvent.ACTION_MOVE:
          case MotionEvent.ACTION_UP:
            myLine.xEnd = event.getX();
            myLine.yEnd = event.getY();
            invalidate();
            lineList.add(myLine); 
            break;

          default:
            Log.d("mock it up", "Unknown touch event  " + event.toString());
            return false;
        }
        return true;

     }
  };

 final OnTouchListener drawDashedLineListener = new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {

        FirstActivity.ll.setVisibility(LinearLayout.GONE);

        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
             return true;

          case MotionEvent.ACTION_MOVE:
          case MotionEvent.ACTION_UP:

            break;

          default:
            Log.d("mock it up", "Unknown touch event  " + event.toString());
            return false;
        }
        return true;

    }
 };

final OnTouchListener drawCircleListener = new OnTouchListener(){

    public boolean onTouch(View v, MotionEvent event) {

        FirstActivity.ll.setVisibility(LinearLayout.GONE);

        float eventX = event.getX();
        float eventY = event.getY();



        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
           //  path.moveTo(eventX, eventY);
              Toast.makeText(getContext(), "action down - circle",Toast.LENGTH_SHORT).show();
              myCircle = new MyCircle();
              myCircle.firstX = eventX;
              myCircle.firstY = eventY;

            // There is no end point yet, so don't waste cycles invalidating.
            return true;

          case MotionEvent.ACTION_MOVE:

          case MotionEvent.ACTION_UP:
            myCircle.lastX = eventX;
            myCircle.lastY = eventY;

            myCircle.radius = getRadius(myCircle.firstX,myCircle.firstY,myCircle.lastX,myCircle.lastY);

            circleList.add(myCircle);

            invalidate();
            break;

          default:
            Log.d("mock it up", "Unknown touch event  " + event.toString());
            return false;
        }
  return true;
    }

};

final OnTouchListener drawOvalListener = new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {

            FirstActivity.ll.setVisibility(LinearLayout.GONE);

            switch (event.getAction()) {
              case MotionEvent.ACTION_DOWN:
                myOval = new MyOval();
                myOval.setX1(event.getX());
                myOval.setY1(event.getY());
                // There is no end point yet, so don't waste cycles invalidating.
                return true;

              case MotionEvent.ACTION_MOVE:
              case MotionEvent.ACTION_UP:

                  myOval.setX2(event.getX());
                  myOval.setY2(event.getY());

                  invalidate();
                  ovalList.add(myOval);

              default:
                Log.d("mock it up", "Unknown touch event  " + event.toString());
                return false;
            }

        }
    };

final OnTouchListener drawRectangleListener = new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {

            FirstActivity.ll.setVisibility(LinearLayout.GONE);

            switch (event.getAction()) {
              case MotionEvent.ACTION_DOWN:
                  myRectangle = new MyRectangle();
                  myRectangle.setX1(event.getX());
                  myRectangle.setY1(event.getY());
                return true;

              case MotionEvent.ACTION_MOVE:

              case MotionEvent.ACTION_UP:

                  myRectangle.setX2(event.getX());
                  myRectangle.setY2(event.getY());
                  invalidate();
                  rectangleList.add(myRectangle);

                break;

              default:
                Log.d("mock it up", "Unknown touch event  " + event.toString());
                return false;
            }


            return true;
        }
};


final OnTouchListener eraseListener = new OnTouchListener() {


};


final OnTouchListener drawFreeHandListener = new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {

        FirstActivity.ll.setVisibility(LinearLayout.GONE);

        float eventX = event.getX();
        float eventY = event.getY();



        // Include half the stroke width to avoid clipping.
        invalidate(
            (int) (dirtyRect.left - HALF_STROKE_WIDTH),
            (int) (dirtyRect.top - HALF_STROKE_WIDTH),
            (int) (dirtyRect.right + HALF_STROKE_WIDTH),
            (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

        lastTouchX = eventX;
        lastTouchY = eventY;

        return true;
    }
};


float xStart,yStart;
final OnTouchListener textListener = new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        FirstActivity.ll.setVisibility(LinearLayout.GONE);

    //  Toast.makeText(getContext(), "add some text", Toast.LENGTH_SHORT).show();


        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
              //
              setInputDialog();
              xStart = event.getX();
              yStart = event.getY();
              alert.show();
            break;

          case MotionEvent.ACTION_MOVE:
          case MotionEvent.ACTION_UP:
            //  setInputDialog();
                  break;

          default:
            Log.d("mock it up", "Unknown touch event  " + event.toString());
            return false;
        }


        return true;
    }
};

/**
 * Called when replaying history to ensure the dirty region includes all
 * points.
 */
private void expandDirtyRect(float historicalX, float historicalY) {
  if (historicalX < dirtyRect.left) {
    dirtyRect.left = historicalX;
  } else if (historicalX > dirtyRect.right) {
    dirtyRect.right = historicalX;
  }
  if (historicalY < dirtyRect.top) {
    dirtyRect.top = historicalY;
  } else if (historicalY > dirtyRect.bottom) {
    dirtyRect.bottom = historicalY;
  }
}

/**
 * Resets the dirty region when the motion event occurs.
 */
private void resetDirtyRect(float eventX, float eventY) {

  // The lastTouchX and lastTouchY were set when the ACTION_DOWN
  // motion event occurred.
  dirtyRect.left = Math.min(lastTouchX, eventX);
  dirtyRect.right = Math.max(lastTouchX, eventX);
  dirtyRect.top = Math.min(lastTouchY, eventY);
  dirtyRect.bottom = Math.max(lastTouchY, eventY);
}


public void setMode(int mode){
    switch(mode){
    case 1://draw line
        Toast.makeText(getContext(), "draw line", Toast.LENGTH_SHORT).show();
        setOnTouchListener(drawLineListener);
        break;
    case 2://draw dashed line
        Toast.makeText(getContext(), "dashed line", Toast.LENGTH_SHORT).show();
        break;
    case 3:// draw circle
        setOnTouchListener(drawCircleListener);
        break;
    case 4: //draw oval
        setOnTouchListener(drawOvalListener);
        break;
    case 5: //draw rectangle
        setOnTouchListener(drawRectangleListener);
        break;
    case 6: //erase
        setOnTouchListener(eraseListener);
        break;
    case 7: //free-hand
        setOnTouchListener(drawFreeHandListener);
        break;
    case 8:
        setOnTouchListener(textListener);
        break;

    }
}

static Bitmap bitmap;
private Canvas myCanvas;
public Paint myPaint;

public void setImage(Bitmap b){
    Toast.makeText(getContext(), "set Bitmap",Toast.LENGTH_SHORT).show();
    bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
    myCanvas = new Canvas(bitmap);

    myPaint = new Paint();
    myPaint.setColor(Color.YELLOW);
    myPaint.setAntiAlias(true);
    myPaint.setStrokeWidth(8);

    invalidate();
}

public void changeColor(int color){
    paint = new Paint(paint);
    paint.setColor(color);
    //myPaint.setColor(color);
}

public float getRadius(float x1,float y1,float x2,float y2){
      float r = (float) (Math.sqrt((double)(Math.pow((y2-y1), 2.0)+Math.pow((x2-x1), 2.0)))/2);
      return r;
  }

public float getCircleMidPointX(float x1,float x2){
      return (x1+x2)/2;
  }

public float getCircleMidPointY(float y1,float y2){
      return (y1+y2)/2;
  }

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
       mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);            
       Canvas canvas = new Canvas(mBitmap);  
       canvas.drawColor(Color.GREEN);
           super.onSizeChanged(w, h, oldw, oldh);
    }

}

我附上了我的代码,以便更有用地了解我的问题在哪里。希望您能够帮助我。先感谢您 :)

4

1 回答 1

0

您可以使用以下代码清除画布。还要确保重置绘图工具。

提供一个新的画布来绘制和重置绘图工具。

在您的 FirstActivity 中

      myView.clear();

在您的 Canvas 视图中创建一个函数,例如 clear

public void clear()
{
  mBitmapPaint = new Paint(Paint.DITHER_FLAG);
  mBitmap = Bitmap.createBitmap(320,480,Bitmap.Config.ARGB_8888);
  mCanvas = new Canvas(mBitmap);  

       //reset drawing tools. reset other drawing tools. (linepaint, cirlce paint..)        

  mPaint = new Paint();
  mPaint.setAntiAlias(true);
  mPaint.setDither(true);
  mPaint.setColor(0xFFFF0000);
  mPaint.setStyle(Paint.Style.STROKE);
  mPaint.setStrokeJoin(Paint.Join.ROUND);
  mPaint.setStrokeCap(Paint.Cap.ROUND);
  mPaint.setStrokeWidth(0);
  invalidate(); //refresh your view. try this
}
于 2013-03-26T21:35:47.123 回答