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();
}
Related
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
private DrawingView drawView;
int mColor;
String savedFilePath = "";
public static ArrayList<Path> undonePaths = new ArrayList<Path>();
public static ArrayList<Path> paths = new ArrayList<Path>();
//buttons
Canvas bitmapCanvas;
RelativeLayout mRelativeLayoutScreenShot;
static String mImagePath;
private ImageButton currPaint, drawBtn, eraseBtn, newBtn, saveBtn;
//sizes
private float smallBrush, mediumBrush, largeBrush;
ImageButton mImageViewPicklColor;
private boolean isFileAlreadySaved = false;
ImageButton mImageButtonList;
ImageButton mImageButtonShare;
File file;
Bitmap bitmap;
Button mButtonUNDo;
Dialog mDialogDate;
Button mButtonRedo;
boolean isStartAdl=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDialogDate= new Dialog(MainActivity.this, android.R.style.Theme_NoTitleBar| android.R.style.Theme_Translucent|android.R.style.Theme_Holo_Dialog);
mDialogDate.setCancelable(true);
mDialogDate.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
#Override
protected void onResume() {
super.onResume();
savedFilePath="";
mColor = 0xff0000ff;
//get drawing view
mButtonUNDo=(Button)findViewById(R.id.btn_undo);
mButtonRedo=(Button)findViewById(R.id.btn_redo);
drawView = (DrawingView)findViewById(R.id.drawing);
mImageViewPicklColor=(ImageButton)findViewById(R.id.pick_color);
RelativeLayout paintLayout = (RelativeLayout)findViewById(R.id.paint_colors);
mImageButtonShare=(ImageButton)findViewById(R.id.share);
mImageButtonList=(ImageButton)findViewById(R.id.list);
mRelativeLayoutScreenShot=(RelativeLayout)findViewById(R.id.rr_draw);
mImageButtonList.setOnClickListener(this);
//sizes from dimensions
smallBrush = getResources().getInteger(R.integer.small_size);
mediumBrush = getResources().getInteger(R.integer.medium_size);
largeBrush = getResources().getInteger(R.integer.large_size);
//draw button
drawBtn = (ImageButton)findViewById(R.id.draw_btn);
drawBtn.setOnClickListener(this);
File direct = new File(Environment.getExternalStorageDirectory() + "/androidpaint");
if(!direct.exists())
{
if(direct.mkdir());//directory is created;
}
mImagePath = Environment.getExternalStorageDirectory() + "/androidpaint";
//set initial size
drawView.setBrushSize(mediumBrush);
//erase button
eraseBtn = (ImageButton)findViewById(R.id.erase_btn);
eraseBtn.setOnClickListener(this);
//new button
newBtn = (ImageButton)findViewById(R.id.new_btn);
newBtn.setOnClickListener(this);
//save button
saveBtn = (ImageButton)findViewById(R.id.save_btn);
saveBtn.setOnClickListener(this);
mButtonRedo.setOnClickListener(this);
mButtonUNDo.setOnClickListener(this);
mImageViewPicklColor.setOnClickListener(this);
mImageButtonShare.setOnClickListener(this);
drawView.setErase(false);
drawView.setBrushSize(drawView.getLastBrushSize());
drawView.setColor(mColor);
if (isStartAdl==true) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
#Override
public void onClick(View view){
if (view.getId()==R.id.btn_undo) {
System.out.println("UNDO "+paths.size());
if (paths.size() > 0) {
undonePaths.add(paths
.remove(paths.size() - 1));
drawView.invalidate();
}
}
else if(view.getId()==R.id.erase_btn)
{
drawView.setErase(true);
}
else if (view.getId()==R.id.btn_redo) {
if (undonePaths.size()>0) {
paths.add(undonePaths.remove(undonePaths.size()-1));
drawView.invalidate();
}
}
});
}
DrawingView.java
public class DrawingView extends View {
private float mX, mY;
private static final float TOUCH_TOLERANCE = 0;
//drawing path
private Path drawPath;
//drawing and canvas paint
private Paint drawPaint, canvasPaint;
//initial color
private int paintColor = 0xFF660000;
//canvas
private Canvas drawCanvas;
//canvas bitmap
private Bitmap canvasBitmap;
//brush sizes
private float brushSize, lastBrushSize;
//erase flag
private boolean erase=false;
public DrawingView(Context context, AttributeSet attrs){
super(context, attrs);
setupDrawing();
}
//setup drawing
private void setupDrawing(){
//prepare for drawing and setup paint stroke properties
brushSize = getResources().getInteger(R.integer.medium_size);
lastBrushSize = brushSize;
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(brushSize);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint(Paint.DITHER_FLAG);
System.out.println("cadslfjds");
MainActivity.paths.add(drawPath);
}
//size assigned to view
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}
//draw the view - will be called after touch event
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(canvasPaints);
for (Path p : MainActivity.paths) {
if(colorsMap.size()>0)
{
drawPaint.setColor(colorsMap.get(p));
canvas.drawPath(p, drawPaint);
}
}
drawPaint.setColor(paintColor);
canvas.drawPath(drawPath, drawPaint);
private void touch_start(float x, float y) {
drawPath.reset();
drawPath.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) {
drawPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
drawPath.lineTo(mX, mY);
drawCanvas.drawPath(drawPath, drawPaint);
MainActivity.paths.add(drawPath);
colorsMap.put(drawPath, paintColor);
drawPath = new Path();
drawPath.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;
}
public void setColor(int newColor){
invalidate();
paintColor = newColor;
drawPaint.setColor(paintColor);
}
//set brush size
public void setBrushSize(float newSize){
float pixelAmount = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
newSize, getResources().getDisplayMetrics());
brushSize=pixelAmount;
drawPaint.setStrokeWidth(brushSize);
}
//get and set last brush size
public void setLastBrushSize(float lastSize){
lastBrushSize=lastSize;
}
public float getLastBrushSize(){
return lastBrushSize;
}
//set erase true or false
public void setErase(boolean isErase){
erase=isErase;
if(erase)
drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
else
drawPaint.setXfermode(null);
}
//start new drawing
public void startNew(){
drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
invalidate();
}
When I paint normal picture, it will come like below
When I click erase Button, it will come like below
When I run above code, the issue is when I click erase button then erase not working properly whole picture convert it into black, so any idea how can I solve it ?
Your code is looking perfect, but problem is you are setting white color as a background on canvas while erasing on canvas then white background also is being erased. So you have to again set white background after erasing some portion on canvas.
#Override
protected void onDraw(Canvas canvas) {
//set background white
canvas.drawColor(Color.WHITE);
super.dispatchDraw(canvas);
}
Check this demo code
All you're doing in setErase is setting a porter duff mode. You aren't actually redrawing anything. At a minimum you need to call invalidate to update the screen.
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.
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 have created SurfaceView class for drawing on the view by onTouch method... i have read and learned some sample codes about the SurfaceView and Drawing Activity and created the following class:
public class DrawingSurface extends SurfaceView implements
SurfaceHolder.Callback{
private DrawingThread drawingthread;
public Paint mPaint;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private float cx = 0, cy = 0;
private boolean easer = false;
private boolean touch = false;
private Paint mEarserPaint;
int count = 0;
public DrawingSurface(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
}
public DrawingSurface(Context context) {
super(context);
getHolder().addCallback(this);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
System.out.println("onSizeChange");
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
System.out.println("onSurfaceChange");
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("onSurfaceCreated");
// For drawing that is called in the onDraw method
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xF0000000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
mEarserPaint = new Paint();
mEarserPaint.setAntiAlias(true);
mEarserPaint.setDither(true);
mEarserPaint.setColor(0xF0000000);
mEarserPaint.setStyle(Paint.Style.STROKE);
mEarserPaint.setStrokeJoin(Paint.Join.ROUND);
mEarserPaint.setStrokeCap(Paint.Cap.ROUND);
mEarserPaint.setStrokeWidth(12);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
drawingthread = new DrawingThread(getHolder(), this);
drawingthread.setRunning(true);
drawingthread.start();
setFocusable(true);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println("OnDestroy");
boolean retry = true;
drawingthread.setRunning(false);
while (retry) {
try {
drawingthread.join();
retry = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void onDraw(Canvas canvas) {
// on earser mode draw circal on touch
if (easer && touch) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawCircle(cx, cy, 50, mEarserPaint);
} else {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
// get the touch postion for drawing the circal
cx = event.getX();
cy = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
touch = true;
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
touch = true;
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
touch = false;
break;
}
return true;
}
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;
}
if (easer)
mCanvas.drawPath(mPath, mPaint);
}
private void touch_up() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
}
public void onAttributeChange(Paint paint, boolean e) {
mPaint = paint;
easer = e;
}
public Bitmap getDrawingSurface() {
return mBitmap;
}
}
And this is the thread class for SurfaceView:
public class DrawingThread extends Thread {
private SurfaceHolder drawingHolder;
private DrawingSurface drawingSurface;
private boolean run = false;
public DrawingThread(SurfaceHolder surfaceholder, DrawingSurface surfaceview) {
drawingHolder = surfaceholder;
drawingSurface = surfaceview;
}
public void setRunning(boolean running) {
run = running;
}
#Override
public void run() {
Canvas c;
while (run) {
c = null;
try {
c = drawingHolder.lockCanvas(null);
if (c != null) {
synchronized (drawingHolder) {
drawingSurface.onDraw(c);
}
}
}finally {
if (c != null)
drawingHolder.unlockCanvasAndPost(c);
}
}
}
}
This is working fine form the start but it stop drawing randomly on the view (not crashing) after while (between 5 sec to 3 min) when i keep drawing .. what i figure is that onDraw method stop processing and i don't know why, there is no exception in the log and the onDestory method is not called when onDraw stop responding to my touch's.
hope you can help me with this problem.
I'm not sure why you have the DrawingThread. Your DrawingSurface class overrides onDraw and you call invalidate() to ask for it to be redrawn. That should be sufficient to do what you are trying to do.
I would comment out the DrawingThread and see if it magically comes together for you. I wrote a network whiteboarding app that started from the same sample code that looks like you started from.
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);
}