Skip to content Skip to sidebar Skip to footer

Android Drawing, Erasing And Undoing Action

Here is the code for Drawing and Undoing but unable to join with Erasing. It is either Drawing + Erasing or Drawing + Undoing but cannot three of these. public class Drawing extend

Solution 1:

The below can be used to draw erase, emboss, save to gallery, blur. You can use the code to add undo and redo functionality. The below code works fine. You can slo check FingerPaint.java from the samples folder of your adk under api demos in the grapics folder.

Creating a spray effect on touch draw in android. This link will help you create spray effect by spraying dots.

publicclassFingerPaintActivityextendsGraphicsActivityimplementsColorPickerDialog.OnColorChangedListener {

    private Paint       mPaint;
    private MaskFilter  mEmboss;
    private MaskFilter  mBlur;
    Button b;
    Dialog dialog;
    static MyView mv;
    File f;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LinearLayoutll= (LinearLayout) findViewById(R.id.ll);
    mv= newMyView(this);
    mv.setDrawingCacheEnabled(true);
    ll.addView(mv);
    b= (Button) findViewById(R.id.button1);
    b.setOnClickListener(newOnClickListener()
    {

        @OverridepublicvoidonClick(View v) {
            // TODO Auto-generated method stubfinal CharSequence[] items = {"Pick Color", "Emboss", "Blur","Erase","SaveToGallery"};

            AlertDialog.Builderbuilder=newAlertDialog.Builder(FingerPaintActivity.this);
            builder.setTitle("Options");
            builder.setItems(items, newDialogInterface.OnClickListener() {
                publicvoidonClick(DialogInterface dialog, int item) {

                       if(item==0)
                       {
                           newColorPickerDialog(FingerPaintActivity.this, FingerPaintActivity.this, mPaint.getColor()).show();
                       }
                       if(item==1)
                       {
                           if (mPaint.getMaskFilter() != mEmboss) {
                                mPaint.setMaskFilter(mEmboss);
                            } else {
                                mPaint.setMaskFilter(null);
                            }

                       }
                       if(item==2)
                       {
                           if (mPaint.getMaskFilter() != mBlur) {
                                mPaint.setMaskFilter(mBlur);
                            } else {
                                mPaint.setMaskFilter(null);
                            }
                       }
                       if(item==3)
                       {
                           mPaint.setXfermode(newPorterDuffXfermode(
                                   PorterDuff.Mode.CLEAR));
                       }
                       if(item==4)
                       {

                          saveImage();
                       }
                   }
               });


            builder.show();
        }


    });
    mPaint = newPaint();
    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(20);

    mEmboss = newEmbossMaskFilter(newfloat[] { 1, 1, 1 },
                                   0.4f, 6, 3.5f);

    mBlur = newBlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
}


publicvoidcolorChanged(int color) {
    mPaint.setColor(color);
}


publicclassMyViewextendsView {

    privatestaticfinalfloatMINP=0.25f;
    privatestaticfinalfloatMAXP=0.75f;

    private Bitmap  mBitmap;
    private Canvas  mCanvas;
    private Path    mPath;
    private Paint   mBitmapPaint;
    Context mcontext;

    publicMyView(Context c) {
        super(c);
        mcontext=c;
        mPath = newPath();
        mBitmapPaint = newPaint();
        mBitmapPaint.setColor(Color.RED);
    }

    @OverrideprotectedvoidonSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        mCanvas = newCanvas(mBitmap);
    }

    @OverrideprotectedvoidonDraw(Canvas canvas) {
        canvas.drawColor(0xFFAAAAAA);
        Displaydisplay= ( (Activity) mcontext).getWindowManager().getDefaultDisplay();  
        floatw= display.getWidth(); 
        floath= display.getHeight();
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
        canvas.drawLine(0, 0, w, 0,mBitmapPaint);
        canvas.drawLine(0, 0, 0, h,mBitmapPaint);
        canvas.drawLine(w,h,w,0,mBitmapPaint);
        canvas.drawLine(w, h, 0,h , mBitmapPaint);
        canvas.drawPath(mPath, mPaint);
    }

    privatefloat mX, mY;
    privatestaticfinalfloatTOUCH_TOLERANCE=4;

    privatevoidtouch_start(float x, float y) {
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }
    privatevoidtouch_move(float x, float y) {
        floatdx= Math.abs(x - mX);
        floatdy= 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;
        }
    }
    privatevoidtouch_up() {
        mPath.lineTo(mX, mY);
        // commit the path to our offscreen
        mCanvas.drawPath(mPath, mPaint);
        mPaint.setXfermode(newPorterDuffXfermode(PorterDuff.Mode.SCREEN));
        // kill this so we don't double draw
        mPath.reset();
    }

    @OverridepublicbooleanonTouchEvent(MotionEvent event) {
        floatx= event.getX();
        floaty= 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;
        }
        returntrue;
    }
}
    publicvoidsaveImage()
    {
    AlertDialog.Buildereditalert=newAlertDialog.Builder(FingerPaintActivity.this);
    editalert.setTitle("Please Enter the name with which you want to Save");
    finalEditTextinput=newEditText(FingerPaintActivity.this);
    LinearLayout.LayoutParamslp=newLinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.FILL_PARENT);
    input.setLayoutParams(lp);
    editalert.setView(input);
    editalert.setPositiveButton("OK", newDialogInterface.OnClickListener() {
        publicvoidonClick(DialogInterface dialog, int whichButton) {
        mv.setDrawingCacheEnabled(true);
        String name= input.getText().toString();
        Bitmapbitmap= mv.getDrawingCache();
     Stringroot= Environment.getExternalStorageDirectory().toString();
        FilemyDir=newFile(root + "/MapleBearDraw");    
        myDir.mkdirs();
        Filefile=newFile (myDir, name+".jpg");
        if (file.exists ()) file.delete ();         
        try 
        {
            if(!file.exists())
        {
            file.createNewFile();
        }
            FileOutputStreamostream=newFileOutputStream(file);
            bitmap.compress(CompressFormat.JPEG, 50, ostream);
            ostream.flush();
            ostream.close();  
            mv.invalidate();                            
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }finally
        {

            mv.setDrawingCacheEnabled(false);                           
        }
        }
    });

    editalert.show();   
 }
privatestaticfinalintCOLOR_MENU_ID= Menu.FIRST;
privatestaticfinalintEMBOSS_MENU_ID= Menu.FIRST + 1;
privatestaticfinalintBLUR_MENU_ID= Menu.FIRST + 2;
privatestaticfinalintERASE_MENU_ID= Menu.FIRST + 3;
privatestaticfinalintSRCATOP_MENU_ID= Menu.FIRST + 4;


publicbooleanonCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c');
    menu.add(0, EMBOSS_MENU_ID, 0, "Emboss").setShortcut('4', 's');
    menu.add(0, BLUR_MENU_ID, 0, "Blur").setShortcut('5', 'z');
    menu.add(0, ERASE_MENU_ID, 0, "Erase").setShortcut('5', 'z');
    menu.add(0, SRCATOP_MENU_ID, 0, "SrcATop").setShortcut('5', 'z');

    /****   Is this the mechanism to extend with filter effects?
    Intent intent = new Intent(null, getIntent().getData());
    intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
    menu.addIntentOptions(
                          Menu.ALTERNATIVE, 0,
                          new ComponentName(this, NotesList.class),
                          null, intent, 0, null);
    *****/returntrue;
}

@OverridepublicbooleanonPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    returntrue;
}

@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
    mPaint.setXfermode(null);
    mPaint.setAlpha(0xFF);

    switch (item.getItemId()) {
        case COLOR_MENU_ID:
            newColorPickerDialog(FingerPaintActivity.this, this, mPaint.getColor()).show();
            returntrue;
        case EMBOSS_MENU_ID:
            if (mPaint.getMaskFilter() != mEmboss) {
                mPaint.setMaskFilter(mEmboss);
            } else {
                mPaint.setMaskFilter(null);
            }
            returntrue;
        case BLUR_MENU_ID:
            if (mPaint.getMaskFilter() != mBlur) {
                mPaint.setMaskFilter(mBlur);
            } else {
                mPaint.setMaskFilter(null);
            }
            returntrue;
        case ERASE_MENU_ID:
            mPaint.setXfermode(newPorterDuffXfermode(
                                                    PorterDuff.Mode.CLEAR));
            returntrue;
        case SRCATOP_MENU_ID:
            mPaint.setXfermode(newPorterDuffXfermode(
                                                PorterDuff.Mode.SRC_ATOP));
            mPaint.setAlpha(0x80);
            returntrue;
    }
    returnsuper.onOptionsItemSelected(item);
}

}

Post a Comment for "Android Drawing, Erasing And Undoing Action"