I am working in canvas related application and everything is working fine except clear all function.
I have used this code for creating canvas and it is also having a erase operation but it is erasing manually.
public class CharactersCanvas extends Activity {
public int width;
public int height;
public Arrays paths1;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
Context context;
private Paint circlePaint;
private Path circlePath;
static List<Integer> listFlag;
/* MyView mv; */
DrawingPanel dp;
AlertDialog dialog;
private ArrayList<Path> undonePaths = new ArrayList<Path>();
public ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<String> step = new ArrayList<String>();
FrameLayout frmLayout;
Canvas canvas;
protected static ImageView imageView;
private Integer frameIndex = 0;
public int res;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canvas_screen);
dp = new DrawingPanel(this);
frmLayout = (FrameLayout) findViewById(R.id.frameLayout1);
imageView=(ImageView) findViewById(R.id.imageView5);
frmLayout.addView(dp);
Bundle bundle = this.getIntent().getExtras();
res = bundle.getInt("resourseInt");
imageView.setImageResource(res);
frameIndex = (bundle != null && bundle.getInt("image") != 0) ? HomeScreen.characters.indexOf(bundle.getInt("image")) : frameIndex;
System.out.println(" Blank " + frameIndex);
frmLayout.setBackgroundResource((int)HomeScreen.characters.get(frameIndex));
/*
* if(){ dp.setBackgroundResource(R.drawable.atemplate); }
*/
((Button) findViewById(R.id.clear_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
paths = new ArrayList<Path>();
if (paths != null)
paths.clear();
if(dp !=null)
dp.invalidate();
}
});
((Button) findViewById(R.id.next_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
paths = new ArrayList<Path>();
if (frameIndex < (HomeScreen.characters.size() - 1)) {
if (paths != null)
paths.clear();
if (dp != null)
dp.invalidate();
System.out.println(" Size is "
+ HomeScreen.characters.size());
frmLayout
.setBackgroundResource((int) HomeScreen.characters
.get(frameIndex != HomeScreen.characters
.size() ? ++frameIndex
: frameIndex));
}
}
});
((Button) findViewById(R.id.previous_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (frameIndex >= 0) {
paths = new ArrayList<Path>();
if (paths != null)
paths.clear();
if (dp != null)
dp.invalidate();
frmLayout
.setBackgroundResource((int) HomeScreen.characters
.get(frameIndex == 0 ? frameIndex
: --frameIndex));
}
}
});
((Button) findViewById(R.id.letters_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MediaPlayer mPlayer = MediaPlayer.create(
CharactersCanvas.this, R.raw.one_sound);
mPlayer.start();
Intent intent = new Intent(getApplicationContext(),
CharactersGridView.class);
intent.putExtra("resourseInt", res);
// integerList is
// ArrayList<Integer>
startActivity(intent);
/*
* startActivity(new Intent(CharactersCanvas.this,
* CharactersGridView.class));
*/
}
});
((Button) findViewById(R.id.home_buttonn))
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MediaPlayer mPlayer = MediaPlayer.create(
CharactersCanvas.this, R.raw.one_sound);
mPlayer.start();
startActivity(new Intent(CharactersCanvas.this,
HomeScreen.class));
finish();
}
});
}
private Paint mPaint;
private MaskFilter mEmboss;
private MaskFilter mBlur;
public class DrawingPanel extends View implements OnTouchListener {
private Canvas mCanvas;
private Path mPath;
private Paint mPaint, circlePaint, outercirclePaint;
// 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(false);
circlePaint.setAntiAlias(false);
mPaint.setAntiAlias(false);
mPaint.setColor(0xFFFF0000);
outercirclePaint.setColor(0x44FFF000);
circlePaint.setColor(0xF57F35);
outercirclePaint.setStyle(Paint.Style.FILL_AND_STROKE);
circlePaint.setStyle(Paint.Style.FILL);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
outercirclePaint.setStrokeWidth(10);
mCanvas = new Canvas();
mPath = new Path();
paths.add(mPath);
}
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) {
if (paths != null && paths.size() > 0) {
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;
}
}
}
I want to clear all the scribles using a single button .How to do this ?Any idea will be really usefull.
to clear the canvas's content you could draw a color,
canvas.drawColor(Color.TRANSPARENT)
for instance.
Related
I'm working on a drawing app but facing some undo problems. When i paint into the image and then press the undo button it won't undo my last action. I'm stuck on it. I'm using floodfill algorithm.
Here is the image below
Look at the Undo function in the code below, i think i did it right but please check it and tell me where is the actual problem.
public class MainActivity extends AppCompatActivity implements
View.OnTouchListener {
Button red, blue, yellow, undo;
Paint paint;
private RelativeLayout drawingLayout;
private MyView myView;
private ArrayList<Path> paths = new ArrayList<>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = new MyView(this);
drawingLayout = (RelativeLayout) findViewById(R.id.relative_layout);
drawingLayout.addView(myView);
red = (Button) findViewById(R.id.btn_red);
blue = (Button) findViewById(R.id.btn_blue);
yellow = (Button) findViewById(R.id.btn_yellow);
undo = (Button) findViewById(R.id.undo);
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.RED);
}
});
yellow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.YELLOW);
}
});
blue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.BLUE);
}
});
undo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myView.onClickUndo();
}
});
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
public class MyView extends View {
final Point p1 = new Point();
Bitmap mBitmap;
ProgressDialog pd;
Canvas canvas;
private Path path;
public MyView(Context context) {
super(context);
paint = new Paint();
paint.setAntiAlias(true);
pd = new ProgressDialog(context);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(5f);
mBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.gp1_1).copy(Bitmap.Config.ARGB_8888, true);
this.path = new Path();
}
public void onClickUndo() {
if (paths.size()>0) {
undonePaths.add(paths.remove(paths.size()-1));
invalidate();
} else {
Toast.makeText(getContext(), getString(R.string.nomore), Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDraw(Canvas canvas) {
this.canvas = canvas;
paint.setColor(Color.GREEN);
canvas.drawBitmap(mBitmap, 0, 0, paint);
for (Path p : paths) {
canvas.drawPath(p, paint);
}
canvas.drawPath(path,paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
p1.x = (int) x;
p1.y = (int) y;
final int sourceColor = mBitmap.getPixel((int) x, (int) y);
final int targetColor = paint.getColor();
new TheTask(mBitmap, p1, sourceColor, targetColor).execute();
paths.add(path);
invalidate();
}
return true;
}
public void clear() {
path.reset();
invalidate();
}
public int getCurrentPaintColor() {
return paint.getColor();
}
class TheTask extends AsyncTask<Void, Integer, Void> {
Bitmap bmp;
Point pt;
int replacementColor, targetColor;
public TheTask(Bitmap bm, Point p, int sc, int tc) {
this.bmp = bm;
this.pt = p;
this.replacementColor = tc;
this.targetColor = sc;
pd.setMessage(getString(R.string.wait));
pd.show();
}
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
FloodFill f = new FloodFill();
f.floodFill(bmp, pt, targetColor, replacementColor);
return null;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
invalidate();
}
}
}
public class FloodFill {
public void floodFill(Bitmap image, Point node, int targetColor,
int replacementColor) {
int width = image.getWidth();
int height = image.getHeight();
int target = targetColor;
int replacement = replacementColor;
if (target != replacement) {
Queue<Point> queue = new LinkedList<Point>();
do {
int x = node.x;
int y = node.y;
while (x > 0 && image.getPixel(x - 1, y) == target) {
x--;
}
boolean spanUp = false;
boolean spanDown = false;
while (x < width && image.getPixel(x, y) == target) {
image.setPixel(x, y, replacement);
if (!spanUp && y > 0
&& image.getPixel(x, y - 1) == target) {
queue.add(new Point(x, y - 1));
spanUp = true;
} else if (spanUp && y > 0
&& image.getPixel(x, y - 1) != target) {
spanUp = false;
}
if (!spanDown && y < height - 1
&& image.getPixel(x, y + 1) == target) {
queue.add(new Point(x, y + 1));
spanDown = true;
} else if (spanDown && y < height - 1
&& image.getPixel(x, y + 1) != target) {
spanDown = false;
}
x++;
}
} while ((node = queue.poll()) != null);
}
}
}
}
I am working on canvas application and I have created a canvas with color picker ,Undo,Redo and clear functions and it is also working fine.Now, I want to validate whether the user is currently drawing a line on the background line on the canvas.
For example,
I am having a background image with dotted lines,now I want the user to draw on the dotted lines and I have to validate it whether it is correct or not? Is it possible in canvas and how can I proceed with this?
Could someone give any suggestion about this which will be really help full for me to proceed with next step in my application and my code is here,
public class HomeScreen extends Activity implements ColorPickerDialog.OnColorChangedListener {
public int width;
public int height;
public Arrays paths1;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
Context context;
private Paint circlePaint;
private Path circlePath;
/* MyView mv; */
DrawingPanel dp;
AlertDialog dialog;
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Path> paths = new ArrayList<Path>();
FrameLayout frmLayout;
Canvas canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
dp = new DrawingPanel(this);
frmLayout = (FrameLayout) findViewById(R.id.frameLayout);
frmLayout.addView(dp);
((Button) findViewById(R.id.Clear)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
paths = new ArrayList<Path>();
if (paths != null)
paths.clear();
if (dp != null)
dp.invalidate();
}
});
((Button) findViewById(R.id.Undo)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
dp.invalidate();
}
}
});
((Button) findViewById(R.id.Redo)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (undonePaths.size() > 0) {
paths.add(undonePaths.remove(undonePaths.size() - 1));
dp.invalidate();
}
}
});
((Button) findViewById(R.id.letters)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(HomeScreen.this, Letters.class));
}
});
((Button) findViewById(R.id.color)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCanvas=new Canvas();
new ColorPickerDialog(HomeScreen.this, HomeScreen.this, mPaint.getColor()).show();
}
});
dp.setDrawingCacheEnabled(true);
Bundle extras = getIntent().getExtras();
Integer userName;
if (extras != null) {
userName = extras.getInt("name");
// and get whatever type user account id is
}
dp.setBackgroundResource(R.drawable.atemplate);// set the back
// ground if you wish
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(20);
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
// mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
}
private Paint mPaint;
private MaskFilter mEmboss;
private MaskFilter mBlur;
public void colorChanged(int color) {
mPaint.setColor(color);
}
public class DrawingPanel extends View implements OnTouchListener {
private Canvas mCanvas;
private Path mPath;
private Paint mPaint, circlePaint, outercirclePaint;
// 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(false);
circlePaint.setAntiAlias(false);
mPaint.setAntiAlias(false);
mPaint.setColor(0xFF000000);
outercirclePaint.setColor(0x44FFF000);
circlePaint.setColor(0xF57F35);
outercirclePaint.setStyle(Paint.Style.FILL_AND_STROKE);
circlePaint.setStyle(Paint.Style.FILL);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
outercirclePaint.setStrokeWidth(10);
mCanvas = new Canvas();
mPath = new Path();
paths.add(mPath);
}
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;
}
}
}
Are you thinking to create a app like pattern locker which are in android devices, try to implement like this way.
#Override
public boolean onTouchEvent(MotionEvent event) {
// MotionEvent object holds X-Y values
if(event.getAction() == MotionEvent.ACTION_DOWN) {
String text = "You click at x = " + event.getX() + " and y = " + event.getY();
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
return super.onTouchEvent(event);
}
this link may help
Your programming skills are good. Difficulty here depends on how complicated the lines are. Have you tried saving the position of the dots? and then compare it to getX and getY when the user presses the screen.
I want to clear all the drawn content in the canvas .I tried several ways and none was clicked for me yet.How to clear all the content in canvas android using clear button?
I have clear button to clear the content in canvas android.But I clearly did not know how to delete the content.I am having undo and redo button which is working fine except this clear button.Could some one tell me how to use this clear button and delete the content? My code is here.
public class MainActivity extends Activity {
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Path> paths = new ArrayList<Path>();
/*
* private Button alphabetsButton; private Button lettersButton; private
* Button clearButton;
*/
private FrameLayout frmLayout;
Canvas canvas;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frmLayout = (FrameLayout) findViewById(R.id.frameLayout);
final DrawingPanel dp = new DrawingPanel(MainActivity.this);
frmLayout.addView(dp);
/*
* alphabetsButton=(Button) findViewById(R.id.button1);
* lettersButton=(Button) findViewById(R.id.button2);
*
*
*
* alphabetsButton.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View v) { // TODO Auto-generated method
* stub startActivity(new Intent(MainActivity.this,Letters.class));
* finish(); } });
*/
((Button) findViewById(R.id.Clear)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
paths = new ArrayList<Path>();
paths.clear();
}
});
((Button) findViewById(R.id.Undo)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
dp.invalidate();
}
}
});
((Button) findViewById(R.id.Redo)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (undonePaths.size() > 0) {
paths.add(undonePaths.remove(undonePaths.size() - 1));
dp.invalidate();
}
}
});
}
class DrawingPanel extends View implements OnTouchListener {
private Canvas mCanvas;
private Path mPath;
private Paint mPaint, circlePaint, outercirclePaint;
private Bitmap mBitmap;
private int width;
private int height;
// 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(false);
circlePaint.setAntiAlias(false);
mPaint.setAntiAlias(false);
mPaint.setColor(0xFF000000);
outercirclePaint.setColor(0x44FFF000);
circlePaint.setColor(0xF57F35);
outercirclePaint.setStyle(Paint.Style.FILL_AND_STROKE);
circlePaint.setStyle(Paint.Style.FILL);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(20);
outercirclePaint.setStrokeWidth(15);
mCanvas = new Canvas();
mPath = new Path();
paths.add(mPath);
}
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;
}
}
}
may you should avoid to instantiate paths again before calling clear(), otherwise you'll call clear() on an empty ArrayList:
((Button) findViewById(R.id.Clear)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (paths != null)
paths.clear();
if (dp != null)
dp.invalidate();
}
});
Looks like the paths array list is persisting, try this code:
private ArrayList<Path> _graphics = new ArrayList<Path>()
#Override
public void onClick(View v) {
clear();
}
Bitmap mBitmap;
Paint mPaint;
Canvas mCanvas;
int width,height;
public void clear()
{
_graphics.removeAll(_graphics);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
path = new Path();
invalidate();
}
You can try this:
#Override
public void onClick(DialogInterface dialog, int which) {
mCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
//paths.clear();
//.destroyDrawingCache();
mPath.reset();
dp.invalidate();
}
I am currently developing a coloring app for the kids. Created a canvas of an image for coloring. The image is a PNG and I am trying to color the image so the image does not get covered by the paint or color. I am very close in building the app but the problem is that I am not getting the tip of coloring the image in a way so that the image remains on the front and the color on the back
Here is my code
public class FingerPaint extends Activity {
LinearLayout mainContainer;
LinearLayout buttonContainer;
LinearLayout.LayoutParams ![enter image description here][1]btnParams;
Button btnText, btnSketch, btnColor, btnUndo, btnRedo, btnDone,btnClear;
// MyView drawView;
DrawingPanel drawView;
int lastColor = 0xFFFF0000;
public static final int SUCCESS = 200;
private final String TAG = getClass().getSimpleName();
private String textToDraw = null;
private boolean isTextModeOn = false;
private Canvas mCanvas;
private Path mPath;
private Paint mPaint, mBitmapPaint;
private ArrayList<PathPoints> paths = new ArrayList<PathPoints>();
private ArrayList<PathPoints> undonePaths = new ArrayList<PathPoints>();
private Bitmap mBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
generateViews();
}
public static void displayAlert(Context context, String msg) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setMessage(context.getString(R.string.app_name));
alert.setMessage(msg);
alert.setPositiveButton(context.getString(R.string.btn_ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
private void generateViews() {
btnDone = new Button(this);
btnDone.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
btnDone.setText(getString(R.string.btn_done));
btnText = new Button(this);
btnClear = new Button(this);
btnSketch = new Button(this);
btnColor = new Button(this);
btnUndo = new Button(this);
btnRedo = new Button(this);
mainContainer = new LinearLayout(this);
mainContainer.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mainContainer.setOrientation(LinearLayout.VERTICAL);
buttonContainer = new LinearLayout(this);
buttonContainer.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
buttonContainer.setOrientation(LinearLayout.HORIZONTAL);
btnParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1);
btnText.setText("Text");
btnText.setLayoutParams(btnParams);
btnClear.setText("Clear");
btnClear.setLayoutParams(btnParams);
btnSketch.setText("Sketch");
btnSketch.setLayoutParams(btnParams);
btnColor.setText("Color");
btnColor.setLayoutParams(btnParams);
btnUndo.setText("Undo");
btnUndo.setLayoutParams(btnParams);
btnRedo.setText("Redo");
btnRedo.setLayoutParams(btnParams);
buttonContainer.addView(btnText);
buttonContainer.addView(btnClear);
buttonContainer.addView(btnSketch);
buttonContainer.addView(btnColor);
buttonContainer.addView(btnUndo);
buttonContainer.addView(btnRedo);
drawView = new DrawingPanel(this, lastColor);
drawView.setDrawingCacheEnabled(true);
drawView.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
drawView.layout(0, 0, drawView.getMeasuredWidth(),
drawView.getMeasuredHeight());
drawView.buildDrawingCache(true);
drawView.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1));
mainContainer.addView(btnDone);
mainContainer.addView(drawView);
mainContainer.addView(buttonContainer);
setContentView(mainContainer);
btnSketch.setSelected(true);
btnText.setOnClickListener(new OnClickListener() {
//text
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
resetButtons();
btnText.setSelected(true);
AlertDialog.Builder alert = new AlertDialog.Builder(
FingerPaint.this);
alert.setMessage(getString(R.string.msg_enter_text_to_draw));
final EditText edText = new EditText(FingerPaint.this);
alert.setView(edText);
alert.setPositiveButton(R.string.btn_ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
if (edText.getText().toString().length() > 0) {
textToDraw = edText.getText().toString();
isTextModeOn = true;
displayAlert(FingerPaint.this,
getString(R.string.msg_tap_image));
} else {
displayAlert(
FingerPaint.this,
getString(R.string.msg_enter_text_to_draw));
}
}
});
alert.setNegativeButton(R.string.btn_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
isTextModeOn = false;
}
});
alert.show();
}
});
/// clear
btnClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//mBitmap.eraseColor(Color.TRANSPARENT);
mPath.reset();
paths.removeAll(paths);
undonePaths.removeAll(undonePaths);
drawView.invalidate();
}
});
////sketch
btnSketch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
resetButtons();
btnSketch.setSelected(true);
isTextModeOn = false;
}
});
//color
/* btnColor.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AmbilWarnaDialog dialog = new AmbilWarnaDialog(
FingerPaint.this, lastColor,
new OnAmbilWarnaListener() {
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
// color is the color selected by the user.
colorChanged(color);
}
#Override
public void onCancel(AmbilWarnaDialog dialog) {
// cancel was selected by the user
}
});
dialog.show();
}
});*/
//undo
btnUndo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
drawView.onClickUndo();
}
});//redo
btnRedo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
drawView.onClickRedo();
}
});
//done
btnDone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*Log.v(TAG, "Here");
Bitmap editedImage = Bitmap.createBitmap(drawView
.getDrawingCache());
editedImage = Bitmap.createScaledBitmap(editedImage, 200, 300,
true);
if (editedImage != null) {
Intent intent = new Intent();
//intent.putExtra(ChooseActivity.BITMAP, editedImage);
// AddReportItemActivity.mPhoto =
// drawView.getDrawingCache();
setResult(SUCCESS, intent);
finish();
}
}*/
AlertDialog.Builder editalert = new AlertDialog.Builder(FingerPaint.this);
editalert.setTitle("Please Enter the name with which you want to Save");
final EditText input = new EditText(FingerPaint.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT);
input.setLayoutParams(lp);
editalert.setView(input);
editalert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name= input.getText().toString();
Bitmap bitmap = drawView.getDrawingCache();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File("mnt/sdcard/"+name+".png");
try
{
if(!file.exists())
{
file.createNewFile();
}
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 10, ostream);
ostream.close();
drawView.invalidate();
}
catch (Exception e)
{
e.printStackTrace();
}finally
{
drawView.setDrawingCacheEnabled(false);
}
}
});
editalert.show();
}
});
}
public void resetButtons() {
btnText.setSelected(false);
btnClear.setSelected(false);
btnSketch.setSelected(false);
btnColor.setSelected(false);
btnUndo.setSelected(false);
btnRedo.setSelected(false);
}
public class DrawingPanel extends View implements OnTouchListener {
private int color;
public int x, y;
public DrawingPanel(Context context, int color) {
super(context);
this.color = color;
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(15);
mPaint.setTextSize(30);
//mPaint.setStyle(Style s);
mPath = new Path();
paths.add(new PathPoints(mPath, color, false));
mCanvas = new Canvas();
}
public void colorChanged(int color) {
this.color = color;
mPaint.setColor(color);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// mBitmap = AddReportItemActivity.mPhoto;
//mBitmap = getIntent().getExtras().getParcelable(ChooseActivity.BITMAP);
mBitmap = BitmapFactory.decodeResource(
getApplicationContext().getResources(),
R.drawable.images);
// targetImage.setImageBitmap(srcBitmapLocal);
float xscale = (float) w / (float) mBitmap.getWidth();
float yscale = (float) h / (float) mBitmap.getHeight();
if (xscale > yscale) // make sure both dimensions fit (use the
// smaller scale)
xscale = yscale;
float newx = (float) w * xscale;
float newy = (float) h * xscale; // use the same scale for both
// dimensions
// if you want it centered on the display (black borders)
mBitmap = Bitmap.createScaledBitmap(mBitmap, this.getWidth(),
this.getHeight(), true);
// mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
for (PathPoints p : paths) {
mPaint.setColor(p.getColor());
Log.v("", "Color code : " + p.getColor());
if (p.isTextToDraw()) {
canvas.drawText(p.textToDraw, p.x, p.y, mPaint);
} else {
canvas.drawPath(p.getPath(), mPaint);
}
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 0;
Point p=new Point();
private void touch_start(float x, float y) {
p.x=(int)x;
p.y=(int)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;
int xx=Math.round(mX);
int yy=Math.round(mY);
}
}
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(new PathPoints(mPath, color, false));
}
private void drawText(int x, int y) {
Log.v(TAG, "Here");
Log.v(TAG, "X " + x + " Y " + y);
this.x = x;
this.y = y;
paths.add(new PathPoints(color, textToDraw, true, x, y));
// mCanvas.drawText(textToDraw, x, y, mPaint);
}
#Override
public boolean onTouch(View arg0, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (!isTextModeOn) {
touch_start(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_MOVE:
if (!isTextModeOn) {
touch_move(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (isTextModeOn) {
drawText((int) x, (int) y);
invalidate();
} else {
touch_up();
invalidate();
}
break;
}
return true;
}
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
}
}
public void colorChanged(int color) {
// TODO Auto-generated method stub
lastColor = color;
drawView.colorChanged(lastColor);
}
class PathPoints {
private Path path;
// private Paint mPaint;
private int color;
private String textToDraw;
private boolean isTextToDraw;
private int x, y;
public PathPoints(Path path, int color, boolean isTextToDraw) {
this.path = path;
this.color = color;
this.isTextToDraw = isTextToDraw;
}
public PathPoints(int color, String textToDraw, boolean isTextToDraw,
int x, int y) {
this.color = color;
this.textToDraw = textToDraw;
this.isTextToDraw = isTextToDraw;
this.x = x;
this.y = y;
}
public Path getPath() {
return path;
}
public void setPath(Path path) {
this.path = path;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public String getTextToDraw() {
return textToDraw;
}
public void setTextToDraw(String textToDraw) {
this.textToDraw = textToDraw;
}
public boolean isTextToDraw() {
return isTextToDraw;
}
public void setTextToDraw(boolean isTextToDraw) {
this.isTextToDraw = isTextToDraw;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
}
in your :
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
}
add these lines before canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.save();
canvas.drawColor(0xff000000);
hope it will help
Hi using myview in one class.am drawing some lines,after that if am clicking button then am going to some other class,then again i am coming back to previous class,but here i drawn lines is not there,but in my case i need to show that drawn lines when i come back to previous activity...can you any one suggest me..thnkyou
MainActivity
public class MainActivity extends Activity {
MyView myview;
RelativeLayout rl;
Button b1;
public boolean action = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,Activity2.class);
startActivity(i);
}
});
rl = (RelativeLayout) findViewById(R.id.layout);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
// mPaint.setColor(0xFFFF0000);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(6);
myview = new MyView(this);
myview.setId(004);
RelativeLayout.LayoutParams lp6 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
myview.setLayoutParams(lp6);
// myview.setBackgroundResource(R.drawable.booklet);
lp6.setMargins(10, 100, 10, 10);
// lp6.setMargins(25, 50, 8,70);
rl.addView(myview, lp6);
}
private Paint mPaint;
private Bitmap mBitmap;
public void colorChanged(int color) {
mPaint.setColor(color);
}
public class MyView extends View {
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
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);
// clearAllResources();
}
#Override
protected void onDraw(Canvas canvas) {
if (action) {
invalidate();
}
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private 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) {
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;
}
}
}
Activity2
public class Activity2 extends Activity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acticity2);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(Activity2.this,MainActivity.class);
startActivityForResult(i, 0);
}
});
}
}
Create a line class that has following properties
float startX, float startY, float stopX, float stopY, Paint paint
Then create List to contain your line instances. Each time you create a line, create a new line instance, set its data and add it to the list. In onDraw, iterate through the list and draw each line with the data you stored.
Problem with your code is that you a launching a new instance of activity whenever button is clicked.
Instead of startActivity() , try calling finish() from Activity2.
OR you can use setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
to bring previous instance of MainActivity to front.
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
//finish(); OR
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}