Undo in a drawing app - android

Before I start I would like you to tell that I am using a very improper method for the "undo" operation.
I have a drawing app which will save each strokes you draw on the view, and when you exit the app the final image will be copied to a folder and others will be deleted.
Now when you draw strokes on the view, each file will be saved in a temp. folder and the path of each file will be inserted to the database, this is to implement the undo operation. When the user clicks for undo, the last inserted value(path) will be deleted and the next path will be quired.
My plan is to use this path to draw the image on the view, so each time the user 'undo's , the last path saved in the database will be deleted and the next path will be taken.
Hope you got my idea..!
Now my issue is , I am not able to draw the image to the view,
I have a custom view which draws the stokes.
View
public class MyView extends View {
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;
private Bitmap mBitmap;
private Paint mBitmapPaint;
public MyView(Context c) {
super(c);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mCanvas.drawColor(Color.BLACK);
}
#Override
protected void onDraw(Canvas canvas) {
try{
new SaveFileThread().execute(null); //------->save strokes as files
Log.i("In ondraw log", "Wow "+filename);
if(undoflag=="undo" && nextp!="haha"){
String pat=UnDo();
if(pat!=null){
if(pat==filename){ pat=UnDo(); Log.i("undo called twice", "not again");}
else{
// Bitmap nbmp=LoadBMPsdcard(pat);
//render the SD card image
// canvas.drawBitmap(nbmp, 0, 0, null);
}
}
//the parent onDraw() method.
// super.onDraw(canvas);
}
//canvas.drawColor(000000);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}catch(Exception e){
e.printStackTrace();
}
}
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
mCanvas.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);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
I have a thread that will do the saving,
How can I draw an image from the SD card to this view.
Can any one suggest me any better ideas to do this.
It would be a great help if you have some sample code if you bring a different idea.
Thanks in advance
Happy Coding

Well, I would not store the bitmaps in files at all. If it's a simple drawing app, then you could (I would) just have an arrayList of say 20 Bitmaps and store the bitmaps to the list. If the length ever gets above 20, remove the first item. This will give you some undo buffer and allow you to more easily handle the operation. As for saving to the sd card look here.
~Aedon
Edit 1:
Use this method to create the bitmap of the canvas.
public Bitmap toBitmap(Canvas canvas) {
Bitmap b = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
canvas.setBitmap(b);
draw(canvas);
return b;
}
Sample onToushListener:
new OnTouchListener() {
public void onTouch(View v, MotionEvent e) {
switch(e.getAction()) {
case MotionEvent.ACTION_DOWN: mIsGesturing = true; mCurrentDrawPath.moveTo(...); // Fall through
case MotionEvent.ACTION_MOVE: // create the draw path the way you are now.
case MotionEvent.ACTION_UP: mIsGesturing = false; addNewBufferBitmap(toBitmap(canvas)); break;
}
}
};
And onDraw(canvas) will look similar to this:
public void onDraw(Canvas canvas) {
canvas.drawBitmap(getLastBufferBitmap(), 0, 0, null);
if (mCurrentDrawPath != null) canvas.drawPath(mCurrentDrawPath, mPathPaint);
if (mIsGesturing) mCanvas = canvas;
}

This code is working in my drawing app..
private Slate mSlate;
private TiledBitmapCanvas mTiledCanvas;
public void clickUndo(View unused) {
mSlate.undo();
}
public void undo() {
if (mTiledCanvas == null) {
Log.v(TAG, "undo before mTiledCanvas inited");
}
mTiledCanvas.step(-1);
invalidate();
}

Related

Android undo drawing method on canvas

I created some code that takes a picture and displays the picture, then the user is able to draw on the picture.
I want to implement an undo method. I based my code on many examples I've read. The problem is in my onDraw method - the examples don't use drawBitmap but for me I have to draw the bitmap on the canvas in order for the image to show up.
The code shown displays the image, allows drawing on the image, but does not undo the drawings. I can't figure out what's wrong/how to fix it.
public class PhotoView extends View {
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private ArrayList<Path> paths = new ArrayList<>();
public PhotoView(Context c) {
super(c);
mBitmap = mutableBitmap;
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
//canvas.drawColor(0xFFAAAAAA);
****must call in order for image to show up *****
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
//canvas.drawPath(mPath, mPaint);
for (Path p : paths){
canvas.drawPath(p, mPaint);
}
canvas.drawPath(mPath, mPaint); //real time drawing on canvas
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touchStart(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touchMove(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 touchUp() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
paths.add(mPath);
mPath = new Path();
//mPath.reset();
//paths.add(mPath);
}
public void onClickUndo () {
if (paths.size()>0)
{
paths.remove(paths.size()-1);
invalidate();
}
}
public Bitmap getPic() {
mCanvas.save();
return mBitmap;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touchUp();
invalidate();
break;
}
return true;
}
}
So there are two things you are doing when it comes to Paths that the user draws.
In the method touchUp() : mCanvas.drawPath(mPath, mPaint);
In onDraw() : canvas.drawPath(p, mPaint);
When you call onClickUndo(), the onDraw() things gets undone. But the one in touchUp() is not undone. That's why your Undo doesn't seem to work. Problem is in line mCanvas.drawPath(mPath, mPaint);
Solution:
Do not draw the mPath on mCanvas. When you do this, your mBitmap gets changed (you are drawing your paths on the mBitmap). There is no way to undo this. And this is not what you want. If you want your paths in your mBitmap, so that you can save it in a file or so, do this finally (perhaps have a method like save() and do this in that method).

Android canvas get cleaned when using many path and paint object

Can someone explain me why on earth this piece of code does not draw every object?
public class A extends View {
private Paint paint = new Paint();
private Path path = new Path();
ArrayList<Pair<Path, Paint>> paths = new ArrayList<Pair<Path, Paint>>();
public A(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
for (Pair<Path, Paint> p : paths) {
canvas.drawPath(p.first, p.second);
}
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(3f);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
int color = Color.rgb(new Random().nextInt(255),
new Random().nextInt(255),
new Random().nextInt(255));
paint.setColor(color);
path.reset(); //new stroke, get old one erased
int historySize = event.getHistorySize();
for (int i = 0; i > historySize; i++) {
path.moveTo(eventX, eventY);
}
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
return true;
case MotionEvent.ACTION_UP:
path.lineTo(eventX, eventY);
// End of stroke, add this to the collection
paths.add(new Pair<Path, Paint>(path, paint));
break;
default:
break;
}
// Schedules a repaint.
invalidate();
return true;
}
}
I'm catching every strokes with the onTouchEvent and i create different path/paint ojects stored in a Pair one. Sadly in my OnDraw when I try to draw them all it fails ..
I've read some topic without finding right answer. Each time some people recommend to create and work in a bitmap and draw it to the screen but i'd like to avoid this solution.
Thank's for your help !
The problem is that you always use the same Path and Paint object. You should create new Path and Paint each time MotionEvent.ACTION_DOWN is fired
Remove the path.reset in switch condition. The draw works. But color does change even for previous draw. You resetting the paths which is clearing the previous draw.
I would use a different pair (path and paint) everytime to draw.
In case you want to draw using canvas the below code work's just fine.
I would also add a color picker to allow user to pick color of his choice.
public class MyView extends View {
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
public MyView(Context c) {
super(c);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, 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
mCanvas.drawPath(mPath, mPaint);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
// 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);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
You need to use only one Path and Paint object.
A detailed tutorial on this whole thing can in fact be found here:
Making a basic single touch drawing app on Android - Creative Punch

Android FingerPaint Undo/Redo implementation

I'm working on a test project which is something similar to FingerPaint example in Android SDK Demos. I was trying to implement undo/redo functionality in my project,but the things that I tried didn't work as I expect. I find some questions similar to this over internet and here,but they didn't help me, that's why I'm asking a new question.
Here is some idea what I'm doing actually :
public class MyView extends View {
//private static final float MINP = 0.25f;
//private static final float MAXP = 0.75f;
private Path mPath;
private Paint mBitmapPaint;
public MyView(Context c) {
super(c);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mCanvas.drawColor(Color.WHITE);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, 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
mCanvas.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);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
Any suggestions/ideas/examples which is the best way to implement this kind of functionality on my project?
I don't know if this is what you had in mind but it's how i am doing it. Instead of storing it in only one path, you store an array with all the paths, like this the user can draw many lines, with a small modification you can add multi touch too.
To make the undo and redo, just remove or add the last path path from the paths variable
and store them in a new array. Something like:
public void onClickUndo () {
if (paths.size()>0) {
undonePaths.add(paths.remove(paths.size()-1))
invalidate();
}
else
//toast the user
}
public void onClickRedo (){
if (undonePaths.size()>0) {
paths.add(undonePaths.remove(undonePaths.size()-1))
invalidate();
}
else
//toast the user
}
Here is my modified panel, I cant try it right now but the methods above should work! Hope it helps! (there are few extra variables just remove them :)
private ArrayList<Path> undonePaths = new ArrayList<Path>();
public class DrawingPanel extends View implements OnTouchListener {
private Canvas mCanvas;
private Path mPath;
private Paint mPaint,circlePaint,outercirclePaint;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private float xleft,xright,xtop,xbottom;
public DrawingPanel(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
circlePaint = new Paint();
mPaint = new Paint();
outercirclePaint = new Paint();
outercirclePaint.setAntiAlias(true);
circlePaint.setAntiAlias(true);
mPaint.setAntiAlias(true);
mPaint.setColor(0xFFFFFFFF);
outercirclePaint.setColor(0x44FFFFFF);
circlePaint.setColor(0xAADD5522);
outercirclePaint.setStyle(Paint.Style.STROKE);
circlePaint.setStyle(Paint.Style.FILL);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(6);
outercirclePaint.setStrokeWidth(6);
mCanvas = new Canvas();
mPath = new Path();
paths.add(mPath);
cx = 400*DrawActivity.scale;
cy = 30*DrawActivity.scale;
circleRadius = 20*DrawActivity.scale;
xleft = cx-10*DrawActivity.scale;
xright = cx+10*DrawActivity.scale;
xtop = cy-10*DrawActivity.scale;
xbottom = cy+10*DrawActivity.scale;
}
public void colorChanged(int color) {
mPaint.setColor(color);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
for (Path p : paths){
canvas.drawPath(p, mPaint);
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 0;
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
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath = new Path();
paths.add(mPath);
}
#Override
public boolean onTouch(View arg0, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (x <= cx+circleRadius+5 && x>= cx-circleRadius-5) {
if (y<= cy+circleRadius+5 && cy>= cy-circleRadius-5){
paths.clear();
return true;
}
}
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;
}
}
The best solution is that you implement your own Undo / Redo engine.
Save into an array every single action you perform in an array (ie. [0] circle in position x1, y1, [1] line from x2, y2 to x3, y3, etc)
draw
if you need to undo, clear the canvas and repaint all the n - 1 actions from [0] to [n - 1]
if you undo more just have to to paint from [0] to [n - 2] etc
I hope it gives you a hint
Cheers!
One way to implement a do/redo functionality is to encapsulate a method call and all info needed for the call in an object so that you can store it and call it later - the Command Pattern.
In this pattern, each action has its own object: DrawCircleCommand, DrawPathCommand, FillColorCommand, etc. In each object the draw() method is implemented in a unique way but is always called as draw(Canvas canvas) which allows the CommandManager to iterate through the commands. To undo you iterate over the objects calling the undo() method;
Each command object implements an Interface
public interface IDrawCommand {
public void draw(Canvas canvas);
public void undo();
}
An object would look like:
public class DrawPathCommand implements IDrawCommand{
public Path path;
public Paint paint;
public void setPath(path){
this.path = path
}
public void draw(Canvas canvas) {
canvas.drawPath( path, paint );
}
public void undo() {
//some action to remove the path
}
}
Your commands are added to the CommandManager:
mCommandManager.addCommand(IDrawCommand command)
and to undo a command you just call:
mCommandManager.undo();
The CommandManager stores the commands in a data structure e.g. list that allows it to iterative over the command objects.
You can find a complete tutorial here on how to implement the Command Pattern with do/undo for Canvas drawing on Android.
Here is a another tutorial on how implement the Command Pattern in Java;
Fortunately,I solved this today. I find a way to do this.Something like:
private ArrayList<Path> paths = new ArrayList<>();
private ArrayList<Path> undonePaths = new ArrayList<>();
public void undo() {
if (paths.size() > 0) {
LogUtils.d("undo " + paths.size());
clearDraw();
undonePaths.add(paths.remove(paths.size() - 1));
invalidate();
}
}
public void redo() {
if (undonePaths.size() > 0) {
LogUtils.d("redo " + undonePaths.size());
clearDraw();
paths.add(undonePaths.remove(undonePaths.size() - 1));
invalidate();
}
}
public void clearDraw() {
mBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
mCanvas.setBitmap(mBitmap);
invalidate();
}
public void clear() {
paths.clear();
undonePaths.clear();
invalidate();
}
in Activity.
private DrawView mDrawView;
if (v == mIvUndo) {
mDrawView.undo();
} else if (v == mIvRedo) {
mDrawView.redo();
in xml
<com.cinread.note.view.DrawView
android:id="#+id/paintView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
If you have a better solution you can contact me.
[here is my blog that I write in
http://blog.csdn.net/sky_pjf/article/details/51086901]
I think that in this case you can use two canvases. You know when user starts drawing and when finishes. So, in touch_start you can create copy of your current canvas. When user clicks undo you replace your current canvas with previously saved.
This should guarantee that you will have previous state of picture, but I am not sure about performance.

how to perform undo operation into paints in android

hi i need perform undo operation in paints.some one suggest use command pattern but i am not getting command pattern.is there any solution is there. help me how to do undo.
i draw paints using below code.
BookType3.class:
public class BookType3 extends Activity implements OnClickListener{
MyView myview;
int counter=0;
private Paint mBitmapPaint;
TextView t1,t2;
private Bitmap mBitmap;
public static boolean action=false;
Button back,erase,undo,save,home;
int image1,image2,image3;
private Canvas mCanvas;
RelativeLayout relative;
RelativeLayout.LayoutParams lp6,lp7;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.booktype1);
List<String> names = Arrays.asList("a","b","c");
relative=(RelativeLayout)findViewById(R.id.relative3);
myview = new MyView(this);
myview.setId(004);
lp6 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
myview.setLayoutParams(lp6);
myview.setBackgroundResource(R.drawable.writingsapce);
undo=(Button)findViewById(R.id.undobutton);
undo.setOnClickListener(this);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(4);
String s1="";
t1=(TextView)findViewById(R.id.button1);
t1.setOnClickListener(this);
t2=(TextView)findViewById(R.id.button2);
t2.setOnClickListener(this);
relative.addView(myview,lp6);
}
private Paint mPaint;
public class MyView extends View{
private Path mPath;
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
if(action)
{
invalidate();
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 2;
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
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
Log.i("x",""+event.getX());
Log.i("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;
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==t1)
{
mPaint.setColor(Color.RED);
t30.setText("A");
t31.setText("a");
t32.setText("Aa");
t30.setTextColor(Color.RED);
t31.setTextColor(Color.RED);
t32.setTextColor(Color.RED);
try{
mBitmap.eraseColor(android.graphics.Color.TRANSPARENT);
Canvas Canvas=new Canvas(mBitmap);
action=true;
myview.onDraw(Canvas);
}catch(IllegalStateException ie){
ie.printStackTrace();
}
}
if(v==t2)
{
t30.setTextColor(Color.BLUE);
t31.setTextColor(Color.BLUE);
t32.setTextColor(Color.BLUE);
mPaint.setColor(Color.BLUE);
t30.setText("B");
t31.setText("b");
t32.setText("Bb");
try{
mBitmap.eraseColor(android.graphics.Color.TRANSPARENT);
Canvas Canvas=new Canvas(mBitmap);
action=true;
myview.onDraw(Canvas);
}catch(IllegalStateException ie){
ie.printStackTrace();
}
}
if(v==undo)
{
}
}
}
Instead of the Command Pattern, I think you should use the Memento Pattern, which is designed for things like undo and redo. There are two ways to implement this pattern. Either by saving deltas, or by saving entire states. Saving states would be easiest in your situation, but it has larger memory footprint. This would involve writing a bitmap to the filesystem every time the user modifies the main bitmap. You could decide on a constant number of undo steps (e.g. 10), and then save the 10 most recent bitmaps. Saving deltas would be more complex. You would implement it by recording the touch events, color, brush, etc. of each paint action. You can then playback and/or rollback individual actions using the motion events. Saving deltas would take significantly less memory, and you would be able to store many more actions and you wouldn't have to write to the filesystem.
private Slate mSlate;
private TiledBitmapCanvas mTiledCanvas;
public void clickUndo(View unused) {
mSlate.undo();
}
public void undo() {
if (mTiledCanvas == null) {
Log.v(TAG, "undo before mTiledCanvas inited");
}
mTiledCanvas.step(-1);
invalidate();
}

how to draw text on view?

i am new to android. I want to develop one simple application that can allow user to draw anything on screen like allowing user to draw shapes or signature on screen (View).in J2ME we can use pointerDragged() method but i dont know how to do it in android.i tried with onTouchEvent(MotionEvent) but not able to do. Please help.
Thanks a lot. Its working very fine. But one problem is there, Drawing is not that much smooth, i mean when i tried to drag the screen drawing is very bold and i want to restrict the user to draw in limited area. Please suggest me. Awaiting for your valuable suggestions.
One way to achieve is to create a view overriding onDraw(Canvas v),onTouchEvent(MotionEvent e) and onSizeChanged(int w, int h, int oldw, int oldh). Below is code snippet to it. I believe it is self-explanatory.
public class MyView extends View {
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
public MyView(Context c) {
super(c);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFFFFFFF);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, 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
mCanvas.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);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
All you have to do is to call setContentView(new MyView(this)); from your activity class. Hope this will help you.
**Disclaimer: The code snippet isn't mine. I also got it from somewhere from the net. The credit goes to whoever wrote it first.

Categories

Resources