Trying to create an Eraser Paint for canvas - android

I am creating a drawing app that utilizes the DrawingSurfaceView class below. In that class i have a Paint Called eraserPaint that the user can toggle on and off.. When on that paint is suppose to eraser what ever is in its path. but instead its just drawing a black line..
When i save out the canvas as a transparent png the eraser is correct but on the screen it shows black..
Screenshot from phone of EraserPaint used to write "Erik" on blob
Saved out PNG from canvas
eraserPaint looks like this:
eraserPaint = new Paint();
eraserPaint.setAlpha(0);
eraserPaint.setColor(Color.TRANSPARENT);
eraserPaint.setStrokeWidth(60);
eraserPaint.setStyle(Style.STROKE);
eraserPaint.setMaskFilter(null);
eraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
eraserPaint.setAntiAlias(true);
the WHOLE class
public KNDrawingSurfaceView(Context c, float width, float height, KNSketchBookActivity parent) {
super(c);
myWidth = width;
myHeight = height;
mBitmap = Bitmap.createBitmap((int) myWidth, (int) myHeight, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
_parent = parent;
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
tile = new Paint();
tileImage = BitmapFactory.decodeResource(getResources(), R.drawable.checkerpattern);
shader = new BitmapShader(tileImage, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
tile.setShader(shader);
mPath = new Path();
eraserPaint = new Paint();
eraserPaint.setAlpha(0x00);
eraserPaint.setColor(Color.TRANSPARENT);
eraserPaint.setStrokeWidth(60);
eraserPaint.setStyle(Style.STROKE);
//eraserPaint.setMaskFilter(null);
eraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
eraserPaint.setAntiAlias(true);
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mCanvas.drawRect(0, 0, myWidth, myHeight, tile);
mCanvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
}
#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 (!_parent.isDrawerOpen()&&mPaint!=null) {
Log.v("onDraw:", "curent paths size:" + paths.size());
//mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
//canvas.drawPath(mPath, mPaint);
for (int i=0;i< paths.size();i++) {
tempPaint = paints.get(i);
eraserPaint.setStrokeWidth(tempPaint.getStrokeWidth());
if(fills.get(i)){
tempPaint.setStyle(Style.FILL_AND_STROKE);
eraserPaint.setStyle(Style.FILL_AND_STROKE);
}else{
tempPaint.setStyle(Style.STROKE);
eraserPaint.setStyle(Style.STROKE);
}
if(erasers.get(i)){
//tempPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawPath(paths.get(i), eraserPaint);
}else{
//tempPaint.setXfermode(null);
canvas.drawPath(paths.get(i), tempPaint);
}
//canvas.drawPath(paths.get(i), tempPaint);
}
if(_parent.toggleFill.isChecked()){
mPaint.setStyle(Style.FILL_AND_STROKE);
eraserPaint.setStyle(Style.FILL_AND_STROKE);
}else{
mPaint.setStyle(Style.STROKE);
eraserPaint.setStyle(Style.STROKE);
}
if(_parent.toggleErase.isChecked()){
//mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawPath(mPath, eraserPaint);
}else{
//mPaint.setXfermode(null);
canvas.drawPath(mPath, mPaint);
}
//canvas.drawPath(mPath, mPaint);
}
}
public void onClickUndo() {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
undonePaints.add(paints.remove(paints.size() - 1));
undoneFills.add(fills.remove(fills.size() - 1));
undoneErasers.add(erasers.remove(erasers.size() - 1));
clearCanvasCache();
invalidate();
} else {
}
_parent.checkButtonStates();
}
public void onClickRedo() {
if (undonePaths.size() > 0) {
paths.add(undonePaths.remove(undonePaths.size() - 1));
paints.add(undonePaints.remove(undonePaints.size() - 1));
fills.add(undoneFills.remove(undoneFills.size() - 1));
erasers.add(undoneErasers.remove(undoneErasers.size() - 1));
clearCanvasCache();
invalidate();
} else {
}
_parent.checkButtonStates();
}
public void onClickClear() {
paths.clear();
paints.clear();
fills.clear();
erasers.clear();
undoneFills.clear();
undonePaths.clear();
undonePaints.clear();
undoneErasers.clear();
clearCanvasCache();
invalidate();
_parent.checkButtonStates();
}
public void saveDrawing() {
FileOutputStream outStream = null;
String fileName = "tempTag";
try {
outStream = new FileOutputStream("/sdcard/" + fileName + ".png");
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
undonePaths.clear();
undonePaints.clear();
undoneFills.clear();
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
if(_parent.toggleErase.isChecked()){
mCanvas.drawPath(mPath, eraserPaint);
erasers.add(true);
paints.add(eraserPaint);
}else{
mCanvas.drawPath(mPath, mPaint);
erasers.add(false);
paints.add(mPaint);
}
// kill this so we don't double draw
paths.add(mPath);
if(_parent.toggleFill.isChecked()){
fills.add(true);
}else{
fills.add(false);
}
if(_parent.toggleErase.isChecked()){
erasers.add(true);
}else{
erasers.add(false);
}
_parent.checkButtonStates();
mPath = new Path();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(mPaint==null &&!_parent._showingAlert){
_parent.showNoPaintAlert();
}
if (!_parent.isDrawerOpen()&&mPaint!=null) {
float x = event.getX();
float y = event.getY();
if (x > myWidth) {
x = myWidth;
}
if (y > myHeight) {
y = myHeight;
}
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;
} else {
return true;
}
}
public void clearCanvasCache() {
mBitmap = Bitmap.createBitmap((int) myWidth, (int) myHeight, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
}
I should add that i am adding this Custom View to a relative layout that has that checkered pattern as the background image..
PLEASE PLEASE PLEASE help.. i need that preview image to NOT show black after an eraser paint was used.. i need it to show the checkered pattern behind.. I know the eraser is working as those black eraser marks save out as transparent.
NEW NOTE
I was playing around and discovered something else thats curious. Experimenting, i tried switching from drawing to the canvas as passed to the onDraw method and directly to the canvas i set up in the contructor called mCanvas and noticed it did not draw as far as i could see.. so I added a log to the onDraw like so:
protected void onDraw(Canvas canvas) {
Log.v("DRAWING SURFACE", "canvas:"+canvas+" mCanvas:"+mCanvas);
which spits out
06-21 11:10:43.994: V/DRAWING SURFACE(4532): canvas:android.view.Surface$CompatibleCanvas#42a8c030 mCanvas:android.graphics.Canvas#431df180

I had this same problem with my app. I even tried the "finger paint" example code and still had the same problem. I was never able to have the eraser work as a path, but I was able to find a workaround. Rather than drawing a path when I erase, I draw a circle (It could be any shape) when the user puts his finger down or there is a "move" event:
case MotionEvent.ACTION_DOWN:
mPaint.setStrokeWidth(25);
mPaint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.CLEAR));
mCanvas.drawCircle(x, y, 10, mPaint);
isErase = true;
invalidate();
}
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
if(isErase)
{
mCanvas.drawCircle(x, y, 20, mPaint);
}
else{
touch_move(x, y);
}invalidate();
break;
It will take some time to incorporate this into your code, but I guarantee you it will take less time than the amount of time you have already spent trying to fix this problem. I can send you more of my PaintView if you think it would be helpful.

Same problem encountered, tried all other solutions found, no luck.
But I got a workaround. You can add a bitmap to store the strokes.
public void init(int width, int height) {
Log.i(TAG,"init with "+width+"x"+height);
foreground = Bitmap.createBitmap(width, height, Config.ARGB_8888);
cacheCanvas = new Canvas();
cacheCanvas.setBitmap(foreground);
}
Whenever there is any touch, record the stroke with the current paint and current stroke width. (the paint could be any color, including the eraser paint)
And then override the onDraw(Canvas) method. As the bitmap supports eraser while the canvas doesn't, we can first draw the resultant image on the bitmap first, and then draw the bitmap to the canvas.
#Override
protected void onDraw(Canvas canvas) {
// Log.i(TAG,"onDraw called");
synchronized (strokes) {
if (strokes.size() > 0) {
for (Stroke s : strokes) {
cacheCanvas.drawPath(s.path, s.color);
}
canvas.drawBitmap(foreground, 0, 0, null);
strokes.clear();
}
}
}
FYI, if the foreground bitmap is very large, the performance will be low. To solve this, we should invalidate only the area which the latest finger touches altered.

This is just a guess: it could be related to hardware acceleration. Try to disable hardware acceleration. If that helps, you can create a bitmap the size of the view, draw all your stuff to that bitmap, and then draw the bitmap into the view's canvas.

For the canvas to erase and invalidate, you have to set the setXfermode of your canvas to null. check the last line of the code.
if(view.getId()==R.id.erase_btn) {
erase_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onDraw.setErase(true);
}
}
}
public void setErase(boolean isErase){
erase=isErase;
if(erase) drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
else drawPaint.setXfermode(null);
}

You can use a boolean variable while choosing eraser (ie. isEraser = true) and in onDraw(), you can draw path if it's not eraser.
#Override
protected void onDraw(Canvas canvas) {
if(!isEraser ){
canvas.drawPath(mPath, mPaint);
}
}

Related

Android: Canvas drawBitmap doesn't work

I am trying to create a canvas that you can draw over a bitmap with. I have loaded the bitmap and there's no problem with it. But when I use drawBitmap I only get a blank screen, while the painting and drawPath still works. I have tried passing the bitmap directly into the constructor as well. Pls help
public class DrawView extends View implements OnTouchListener {
private static final String TAG = "DrawView" ;
private Canvas mCanvas;
private Path mPath;
private Paint mPaint;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
final int defaultBrushSize = 10;
private Bitmap im;
public DrawView(Context context, Intent intent,String fileroot)
{
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.parseColor("#000000"));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.BEVEL);
mPaint.setStrokeCap(Paint.Cap.SQUARE);
mPaint.setAlpha(150);
mPaint.setStrokeWidth(defaultBrushSize);
FileInputStream in = null;
try {
in = new FileInputStream(fileroot+"/"+intent.getStringExtra("image")+".jpg");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bMapArray= new byte[buf.available()];
Log.d(TAG, "onCreate: bMap array: " + bMapArray.toString());
buf.read(bMapArray);
im = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length).copy(Bitmap.Config.ARGB_8888, true);
Log.d(TAG, "onCreate: bmap " + im);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
mPath = new Path();
mCanvas = new Canvas();
mCanvas.drawBitmap(im,null,new Rect(0,0,im.getWidth(),im.getHeight()),null);
}
#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);
}
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
undonePaths.clear();
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
paths.add(mPath);
mPath = new Path();
}
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 setSize(int s){
mPaint.setStrokeWidth(s);
invalidate();
}
#Override
public boolean onTouch(View arg0, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
You aren't backing the Canvas anywhere. Just calling new Canvas, without backing it somewhere, sends the draw commands into a black hole. Generally you back them to an in memory Bitmap object you have to create first. So here you'd want to use canvas = new Canvas(bitmap);
Also note that to get anything to appear on screen, you must draw it to the Canvas passed into onDraw during the onDraw function. So just drawing to a random Canvas, backed or not, will not draw it to the screen.

Android using Canvas to apply an overlay causes null pointer exception

this has been driving me a little crazy today. I've implimented this class which enables me to draw lines over an image file. however I want to be able to to add a template mask at creation time. Whatever I try i.e. within the class or from the calling class it causes a Null pointer exception, if however I put the call into a button in the calling class then I can get it to work?
here is the class I'm using. You can see the commented out section, if I call "coverScreen()" from here it causes the NPE. Also from the main Activity where I create the maskBoard if I call "coverScreen()" it causes NPE. But as mentioned if I add a button, and put the "coverScreen()" into this button onclick then it works?
public class MaskBoard extends View {
private String TAG = "Test APP - maskboard";
private int mx = -1;
private int my = -1;
private Bitmap mainImage = null;
private Bitmap bm = null;
private Paint mPaint = null;
public final int CLOSER = 50;
public final int CLOSE = 100;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
public MaskBoard(Context c, AttributeSet s) {
super(c, s);
String fileToMask = "/__temppic.png";
File imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/temp/");
File imgFile = new File(imagePath+fileToMask);
if (imgFile.exists()) {
bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
Log.i(TAG, "found image");
}
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mPaint = new Paint();
mPaint.setAntiAlias(false);
mPaint.setDither(true);
mPaint.setColor(0xFFFE0000); // FFFF0000
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(50);
/* coverScreen() */
setEraser();
}
public void coverScreen() {
Bitmap maskImage = BitmapFactory.decodeResource(getResources(), R.drawable.mask); //get mask image
maskImage = Bitmap.createScaledBitmap(maskImage, bm.getWidth(), bm.getHeight(), true);
mPaint.setXfermode(null);
mCanvas.drawBitmap(maskImage,0,0,mPaint);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
public void setEraser() {
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
public void setPaint() {
mPaint.setXfermode(null);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.i(TAG, "onsizechanged");
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
Log.i(TAG, "onDraw");
canvas.drawRect(0,0, getWidth(), getHeight(), mPaint);
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(bm, mx, my, null);
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;
Log.i(TAG, " touchdown: X(" + x + "), Y(" + 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;
Log.i(TAG, " touchmove: X(" + x + "), Y(" + 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);
// coverScreen() ;
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}

draw on canvas in different device has different smoothness

In my application i am used canvas to draw a letter.
my code is working .
But my problem is smoothness in different devices.
I am put screen short
1)screen short take from samsung tab 2 7 inch
2) screen short take from google nexus 7 inch.
What is the problem in samsung device why smoothness not working .
I am also download such type of drawing application but not properly working in samsung device.
Please help me .
Below code is used for paint
class MyTView extends View {
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private Matrix matrix = new Matrix();
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
public MyTView(Context c) {
super(c);
mBitmap = Bitmap.createBitmap(display.getWidth(),
display.getHeight(), Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
// set canvas background color white
Paint paint = new Paint();
// paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
mCanvas.drawPaint(paint);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
public MyTView(Context c, AttributeSet atrs ) {
super(c, atrs);
mBitmap = Bitmap.createBitmap(display.getWidth(), display.getHeight(), Bitmap.Config.ARGB_8888);
// mBitmap = Bitmap.createBitmap(display.getWidth(), display.getHeight(), Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
public MyTView(Context c,Bitmap bmp ) {
super(c);
mBitmap = Bitmap.createBitmap(display.getWidth(), display.getHeight(), Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mCanvas.drawBitmap(bmp, 0, 0,null);
}
protected void onDraw(Canvas canvas) {
//canvas.drawBitmap(mBitmap, 0, 0, mTPaint); // ORIGINAL
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); // ORIGINAL
canvas.drawPath(mPath, mTPaint);
}
public void touch_start(float x, float y) {
arrXY.clear();
mPath.moveTo(x, y);
mX = x;
mY = y;
arrXY.add(new XYBean(x, y));
}
public void touch_move(float x, float y) {
arrXY.add(new XYBean(x, 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() {
btn_replay.setBackgroundResource(R.drawable.button_blue);
btn_replay.setTextColor(Color.parseColor("#FFFFFF"));
System.out.println("--- touch up event ------");
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mTPaint);
mPath.reset();
getScreenCap(drawLayout);
}
// mCanvas.drawPath(mPath, mPaint);
++count;
isSet = false;
//arrXY.clear();
System.out.println("After clearing the arrXY: "+arrXY.size());
isStart = true;
postInvalidate();
}
#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();
mCanvas.drawPath(mPath, mTPaint); // edited by shreyash
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
mCanvas.drawPath(mPath, mTPaint); // edited by shreyash
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
// arrXY.clear();
break;
}
return true;
}
}

Regarding Android Paint drawing color

DrawView.java
public class DrawView extends View implements OnTouchListener {
private Canvas mCanvas;
private Path mPath;
public Paint mPaint;
ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private MaskFilter mEmboss;
private MaskFilter mBlur;
private Bitmap im;
public DrawView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
paths.clear();
undonePaths.clear();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(4);
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
mCanvas = new Canvas();
mPath = new Path();
// paths.add(mPath);
im = BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher);
}
#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(Share.cColor);
for (Path p : paths) {
canvas.drawPath(p, mPaint);
}
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPaint.setColor(Share.dColor);
undonePaths.clear();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
Log.e("", "pathsize:::" + paths.size());
Log.e("", "undonepathsize:::" + undonePaths.size());
}
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
paths.add(mPath);
mPath = new Path();
Log.e("", "pathsize:::" + paths.size());
Log.e("", "undonepathsize:::" + undonePaths.size());
}
public void onClickUndo() {
Log.e("", "pathsize:::" + paths.size());
Log.e("", "undonepathsize:::" + undonePaths.size());
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
invalidate();
} else {
}
// toast the user
}
public void onClickRedo() {
Log.e("", "pathsize:::" + paths.size());
Log.e("", "undonepathsize:::" + undonePaths.size());
if (undonePaths.size() > 0) {
paths.add(undonePaths.remove(undonePaths.size() - 1));
invalidate();
} else {
}
// toast the user
}
#Override
public boolean onTouch(View arg0, MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
I am trying to draw finger paint with different colors but whenever i change the color of paint then all previous path or drawing get and draw with updated color i want to draw with different colors how can i do that ? please give me some solutions for this.
To do this, you'd have to create a new Paint for every object drawn. This is because when the Canvas redraws, it references that same Paint object every time, so all paths will use this paint.
Firstly, I would change your paths array to contain both a Paint and a Path. You can achieve this using the Android type Pair.
ArrayList<Pair<Path, Paint>> paths = new ArrayList<Pair<Path, Paint>>();
You will also have to convert your undonePaths variable in this manner.
Then, in your touch_up() method, you need to add this new Paint object.
Paint newPaint = new Paint(mPaint); // Clones the mPaint object
paths.add(new Pair<Path, Paint>(mPath, newPaint));
Lastly, your loop has to be adjusted for this as well:
for (Pair<Path, Paint> p : paths) {
canvas.drawPath(p.first, p.second);
}
This is quite memory intensive, so you will have to take good care to reset these items when they're no longer in use, but to have so many different colors, you must have all of these different Paint objects.

Android Signature Capture [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am working on android application. In my project I have a task regarding signature capture i.e the user should keep his/her signature on the screen of the mobile and once save button is clicked the signature has to stored in the database. I have searched and found some links but still I didn't find the exact solution.
I also tried TouchPaint.java but there I didnt find the xml file for layout.
Could you please suggest us with some sample code? I will be thankful to you....
Here is the working Java version of Has AlTaiar's C# Signature View,
Took me a while to get it to work 100% correctly
public class CaptureSignatureView extends View {
private Bitmap _Bitmap;
private Canvas _Canvas;
private Path _Path;
private Paint _BitmapPaint;
private Paint _paint;
private float _mX;
private float _mY;
private float TouchTolerance = 4;
private float LineThickness = 4;
public CaptureSignatureView(Context context, AttributeSet attr) {
super(context, attr);
_Path = new Path();
_BitmapPaint = new Paint(Paint.DITHER_FLAG);
_paint = new Paint();
_paint.setAntiAlias(true);
_paint.setDither(true);
_paint.setColor(Color.argb(255, 0, 0, 0));
_paint.setStyle(Paint.Style.STROKE);
_paint.setStrokeJoin(Paint.Join.ROUND);
_paint.setStrokeCap(Paint.Cap.ROUND);
_paint.setStrokeWidth(LineThickness);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
_Bitmap = Bitmap.createBitmap(w, (h > 0 ? h : ((View) this.getParent()).getHeight()), Bitmap.Config.ARGB_8888);
_Canvas = new Canvas(_Bitmap);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(_Bitmap, 0, 0, _BitmapPaint);
canvas.drawPath(_Path, _paint);
}
private void TouchStart(float x, float y) {
_Path.reset();
_Path.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 >= TouchTolerance || dy >= TouchTolerance) {
_Path.quadTo(_mX, _mY, (x + _mX) / 2, (y + _mY) / 2);
_mX = x;
_mY = y;
}
}
private void TouchUp() {
if (!_Path.isEmpty()) {
_Path.lineTo(_mX, _mY);
_Canvas.drawPath(_Path, _paint);
} else {
_Canvas.drawPoint(_mX, _mY, _paint);
}
_Path.reset();
}
#Override
public boolean onTouchEvent(MotionEvent e) {
super.onTouchEvent(e);
float x = e.getX();
float y = e.getY();
switch (e.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;
}
public void ClearCanvas() {
_Canvas.drawColor(Color.WHITE);
invalidate();
}
public byte[] getBytes() {
Bitmap b = getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
public Bitmap getBitmap() {
View v = (View) this.getParent();
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
}
I tried Rob Croll's suggestion, which worked good, but it is straight liney, rendering the signature not human looking. If you know what I mean :P
Here is how you append the view on an empty linear layout
LinearLayout mContent = (LinearLayout) findViewById(R.id.linearLayout);
CaptureSignatureView mSig = new CaptureSignatureView(this, null);
mContent.addView(mSig, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
Here is how to get the bytes or Bitmap of the Signature
byte[] signature = mSig.getBytes();
Bitmap signature = mSig.getBitmap();
For anyone looking for a solution you will find one at http://www.mysamplecode.com/2011/11/android-capture-signature-using-canvas.html
It actually writes the signature to file but it's easy enough to change and write to a database instead.
you probably need gesture builder.
i think this link.
http://android-developers.blogspot.com/2009/10/gestures-on-android-16.html
will be usefull to you. if you need to check the signature again.
UPDATE
are you talking about this
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/TouchPaint.html
then this example does not use xml. it has the view as an inner class (MyView)
I know this is an old question, but I needed to implement my own view to capture the signature because I am using MonoForAndroid (C# not Java). So I am adding my View code in here in case somebody needs it.
using System;
using Android.Content;
using Android.Graphics;
using Android.Views;
namespace MyApp.Views
{
public class CaptureSignatureView : View
{
public CaptureSignatureView(Context c, SignatureData signatureData) : base(c)
{
SignatureData = signatureData;
_Path = new Path();
_BitmapPaint = new Paint(PaintFlags.Dither);
_paint = new Paint
{
AntiAlias = true,
Dither = true,
Color = Color.Argb(255, 0, 0, 0)
};
_paint.SetStyle(Paint.Style.Stroke);
_paint.StrokeJoin = Paint.Join.Round;
_paint.StrokeCap = Paint.Cap.Round;
_paint.StrokeWidth = 8;
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
base.OnSizeChanged(w, h, oldw, oldh);
_Bitmap = Bitmap.CreateBitmap(w, (h > 0 ? h : ((View)this.Parent).Height), Bitmap.Config.Argb8888);
_Canvas = new Canvas(_Bitmap);
}
protected override void OnDraw(Canvas canvas)
{
canvas.DrawColor(Color.White);
canvas.DrawBitmap(_Bitmap, 0, 0, _BitmapPaint);
canvas.DrawPath(_Path, _paint);
}
private float _mX, _mY;
private const float TouchTolerance = 4;
private void TouchStart(float x, float y)
{
_Path.Reset();
_Path.MoveTo(x, y);
_mX = x;
_mY = y;
SignatureData.AddPoint(SignatureState.Start, (int)x, (int)y);
}
private void TouchMove(float x, float y)
{
float dx = Math.Abs(x - _mX);
float dy = Math.Abs(y - _mY);
if (dx >= TouchTolerance || dy >= TouchTolerance)
{
_Path.QuadTo(_mX, _mY, (x + _mX) / 2, (y + _mY) / 2);
SignatureData.AddPoint(SignatureState.Move, (int)x, (int)y);
_mX = x;
_mY = y;
}
}
private void TouchUp()
{
if (!_Path.IsEmpty)
{
_Path.LineTo(_mX, _mY);
_Canvas.DrawPath(_Path, _paint);
}
else
{
_Canvas.DrawPoint(_mX, _mY, _paint);
}
SignatureData.AddPoint(SignatureState.End, (int)_mX, (int)_mY);
_Path.Reset();
}
public override bool OnTouchEvent(MotionEvent e)
{
var x = e.GetX();
var y = e.GetY();
switch (e.Action)
{
case MotionEventActions.Down:
TouchStart(x, y);
Invalidate();
break;
case MotionEventActions.Move:
TouchMove(x, y);
Invalidate();
break;
case MotionEventActions.Up:
TouchUp();
Invalidate();
break;
}
return true;
}
public void ClearCanvas()
{
_Canvas.DrawColor(Color.White);
Invalidate();
}
public Bitmap CanvasBitmap()
{
return _Bitmap;
}
public void Clear()
{
ClearCanvas();
SignatureData = new SignatureData();
}
#region Implementation
private Bitmap _Bitmap;
private Canvas _Canvas;
private readonly Path _Path;
private readonly Paint _BitmapPaint;
private readonly Paint _paint;
public SignatureData SignatureData;
#endregion
}
}
Also, I have a blog post here that goes through the details of how to capture the signature. Basically you can do it in two different ways. Either you capture the view with the signature as an image and you save that bitmap (and send it to the server maybe). Or you could just capture a two dimensional array of points and reconstruct the signature in any way you want it.

Categories

Resources