Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 清除位图&;帆布_Java_Android_Bitmap_Android Canvas - Fatal编程技术网

Java 清除位图&;帆布

Java 清除位图&;帆布,java,android,bitmap,android-canvas,Java,Android,Bitmap,Android Canvas,有人知道如何清除位图和画布吗?我认为有些代码是错误的或不完整的。例如,在public void forceRedraw()的FirstActivity.java上,我收到一条消息,在invalidate()上创建一个方法。如果你需要另一门课,就告诉我。我真的不知道哪里会是我的错误。我正在使用以下代码。它有点大,但希望能理解它 这是我的第一个activity.java public class FirstActivity extends Activity implements ColorPicke

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

这是我的第一个activity.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);
    }

}
public类CanvasView扩展视图{
private ArrayList undonePaths=new ArrayList();
私有ArrayList路径=新ArrayList();
专用静态最终浮动行程_宽度=5f;
专用静态最终浮动半冲程宽度=冲程宽度/2;
私人浮动mX,我的;
专用静态最终浮动接触公差=4;
油漆=新油漆();
油漆=新油漆();
路径路径=新路径();
浮动lastTouchX,lastTouchY;
AlertDialog.Builder警报;
RectF ovalRectangle=新的RectF();
RectF dirtyRect=新的RectF();
我的矩形我的矩形;
肌膜肌膜;
我的圈子我的圈子;
我的徒手;
糜棱线;
髓鞘酶;
List eraserList=new ArrayList();
List lineList=new ArrayList();
List freehandList=new ArrayList();
List circleList=新建ArrayList();
List ovalList=new ArrayList();
List rectangleList=新建ArrayList();
公共布尔虚线=false;
公共DashPathEffect dashEffect=新的DashPathEffect(新浮点[]{20,30},0);
私人油漆;
私有位图mBitmap;
公共字符串文本值;
公共画布视图(上下文、属性集属性){
超级(上下文,attrs);
setBackgroundColor(颜色:白色);
如果(android.os.Build.VERSION.SDK_INT>=11)
{
关闭硬件eacc();
}
橡皮擦油漆。设置颜色(颜色。透明);
//橡皮擦paint.setXfermode(新的PorterDuffXfermode(PorterDuff.Mode.CLEAR));
橡皮擦油漆。setAntiAlias(真);
擦除Paint.setStyle(Paint.Style.STROKE);
橡皮擦油漆.设置行程连接(油漆.连接.圆形);
擦除油漆。设置行程宽度(5f);
油漆。设置颜色(颜色。黑色);
绘制.设置样式(绘制.样式.笔划);
paint.setAntiAlias(真);
绘制.设置行程连接(绘制.连接.圆形);
油漆。设置行程宽度(行程宽度);
油漆.尺寸(72);
setMode(7);//默认值=7-自由手;
mBitmap=Bitmap.createBitmap(320480,Bitmap.Config.ARGB_8888);
mBitmapPaint=新油漆(油漆抖动标志);
/*输入对话框*/
//setInputDialog();
}
编辑文本输入;
public void setInputDialog(){
alert=新建AlertDialog.Builder(getContext());
警报。设置标题(“标题”);
alert.setMessage(“写入文本”);
//设置EditText视图以获取用户输入
输入=新编辑文本(getContext());
alert.setView(输入);
alert.setPositiveButton(“确定”,新的DialogInterface.OnClickListener(){
public void onClick(对话框接口对话框,int whichButton){
textValue=input.getText().toString();
Toast.makeText(getContext(),textValue,Toast.LENGTH_SHORT).show();
//做一些有价值的事情!
}
});
alert.setNegativeButton(“取消”,新建DialogInterface.OnClickListener()){
public void onClick(对话框接口对话框,int whichButton){
//取消了。
}
});
//alert.show();
}
专用无效触摸启动(浮动x、浮动y){
撤销海王星。清除();
path.reset();
路径移动到(x,y);
mX=x;
mY=y;
}
私有无效触摸移动(浮动x、浮动y){
float dx=Math.abs(x-mX);
float dy=Math.abs(y-mY);
如果(dx>=接触公差| | dy>=接触公差){
路径四度图(mX,mY,(x+mX)/2,(y+mY)/2);
mX=x;
mY=y;
}
}
私人空间修补(){
lineTo(mX,mY);
Canvas mCanvas=null;
//将路径提交到我们的屏幕外
mCanvas.drawPath(路径,绘制);
//杀了它,这样我们就不会重复抽签了
路径。添加(路径);
路径=新路径();
}
公共无效撤消(){
如果(path.size()>0){
undonePaths.add(path.remove(path.size()-1));
使无效();
}
其他的
{
}
}
公共无效重做(){
如果(undonePaths.size()>0){
add(undonePaths.remove(undonePaths.size()-1));
使无效();
} 
其他的
{
}
}
public void setDashLine(){
虚线=真;
油漆=新油漆();
paint.setPathEffect(dashEffect);
绘制.设置样式(绘制.样式.笔划);
paint.setAntiAlias(真);
绘制.设置行程连接(绘制.连接.圆形);
油漆。设置行程宽度(行程宽度);
}
公共void setNormalLine(){
//油漆。设置颜色(颜色。黑色);
虚线=假;
paint.setPathEffect(空);
绘制.设置样式(绘制.样式.笔划);
paint.setPathEffect(空);
paint.setAntiAlias(真);
绘制.设置行程连接(绘制.连接.圆形);
油漆。设置行程宽度(行程宽度);
}
@塔吉塔皮(11)
public void turnOffHardwareAcc()//启用虚线
{
this.setLayerType(View.LAYER\u TYPE\u软件,null);
}
//公共void setPaint(内部颜色)
@塔吉塔皮(11)
受保护的void onDraw(画布){
paint.setPathEffect(空);
if(位图!=null){
drawBitmap(位图,0,0,绘制);
对于(MyCircle circle:circleList){//绘制圆
myCanvas.drawCircle(getCircleMidPointX(circle.firstX,circle.lastX),getCircleMidPointY(circle.firstY,circle.lastY),circle.radius,myPaint);
}
}
对于(MyLine-line:lineList){//绘制线
如果(虚线)
line.paint.setPathEffect(dashEffect);
其他的
line.paint.setPathEffect(null);
canvas.drawLine(line.xStart、line.yStart、line.xEnd、line.yEnd、line.paint);
}
对于(MyCircle circle:circleList){//绘制圆
canvas.drawCircle(getCircleMidPointX(circle.firstX,circle.lastX),getCircleMidPointY(circle.firstY,circle.lastY),circle.radius,paint);
}
用于(MyOval椭圆形:椭圆形){
oval.paint.setPathEffect(null);
ovalRectangle.set(oval.getX1()、oval.getY1()、oval.getX2()、oval.getY2());
画布。绘制椭圆形(o)
      myView.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
}