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.
Related
I am trying to use the method mCanvas.drawBitmap(iconBitmap,x-100,y-100, mBitmapPaint); on my MotionEvent.ACTION_DOWN event in my custom view class. However, the image I want to show does not appear on the canvas at that point. I am trying to make a paint application where users can draw free hand and insert images at the same time to play with them.
This is my custom view class:
package com.example.shazs.autismate;
public class PaintView extends View {
public static int BRUSH_SIZE = 20;
public static final int DEFAULT_COLOR = Color.RED;
public static final int DEFAULT_BG_COLOR = Color.WHITE;
private static final float TOUCH_TOLERANCE = 4;
private float mX, mY;
private Path mPath;
private Paint mPaint;
private ArrayList<FingerPath> paths = new ArrayList<>();
private int currentColor;
private int backgroundColor = DEFAULT_BG_COLOR;
private int strokeWidth;
private boolean emboss;
private boolean blur;
private MaskFilter mEmboss;
private MaskFilter mBlur;
private Bitmap mBitmap;
private Paint mBitmapPaint;
private Canvas mCanvas;
private Bitmap iconBitmap;
private static AtomicBoolean drawIcon = new AtomicBoolean();
public PaintView(Context context) {
this(context, null);
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(DEFAULT_COLOR);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setXfermode(null);
mPaint.setAlpha(0xff);
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mEmboss = new EmbossMaskFilter(new float[] {1, 1, 1}, 0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(5, BlurMaskFilter.Blur.NORMAL);
}
public void init(DisplayMetrics metrics) {
int height = metrics.heightPixels;
int width = metrics.widthPixels;
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
currentColor = DEFAULT_COLOR;
strokeWidth = BRUSH_SIZE;
}
public void normal() {
emboss = false;
blur = false;
}
public void emboss() {
emboss = true;
blur = false;
}
public void blur() {
emboss = false;
blur = true;
}
public void setPaintColor(int color){
if (currentColor!=color)
Log.d("xyzn","current color changed");
else
Log.d("xyzn","current color not changed");
currentColor=color;
}
public void drawBitmap(Bitmap bm){
drawIcon.set(true);
iconBitmap = bm;
}
public int getPaintColor(){
return currentColor;
}
public void clear() {
backgroundColor = DEFAULT_BG_COLOR;
paths.clear();
normal();
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
mCanvas.drawColor(backgroundColor);
for (FingerPath fp : paths) {
mPaint.setColor(fp.color);
mPaint.setStrokeWidth(fp.strokeWidth);
mPaint.setMaskFilter(null);
if (fp.emboss)
mPaint.setMaskFilter(mEmboss);
else if (fp.blur)
mPaint.setMaskFilter(mBlur);
mCanvas.drawPath(fp.path, mPaint);
}
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.restore();
}
private void touchStart(float x, float y) {
mPath = new Path();
FingerPath fp = new FingerPath(currentColor, emboss, blur, strokeWidth, mPath);
paths.add(fp);
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touchMove(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touchUp() {
mPath.lineTo(mX, mY);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN :
if (drawIcon.get()){
mCanvas.drawBitmap(iconBitmap,x-100,y-100, mBitmapPaint);
mCanvas.save();
break;
}
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE :
if (drawIcon.get())
break;
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP :
if (drawIcon.get()){
drawIcon.set(false);
break;
}
touchUp();
invalidate();
break;
}
return true;
}
}
Main Activity which uses this custom view class and passes the bitmap of object to draw:
public class drawActivity extends AppCompatActivity implements
ColorPickerDialog.OnColorChangedListener {
private PaintView paintView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.css_layout);
paintView = (PaintView) findViewById(R.id.paintView);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
paintView.init(metrics);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.draw:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.apple);
paintView.drawBitmap(bm);
break;
I use drawIcon to see if the user needs to insert icon or just draw freehand.
Interestingly, when I go into application view of my phone to view all currently running applications, the icon/image shows on the canvas. However when I return to the application, it dissappears. It only happens once after I insert the icon, not repeatedly.
OK, I had to remove the line
mCanvas.drawColor(backgroundColor);
from my onDraw(Canvas canvas) method and call invalidate()
I am working on android paint signature application where it has the flexibility to clear the paint and save the canvas as bitmap image. I am facing an issue in this app, whenever i want to save the canvas as bitmap i need to check whether the signature is lengthy enough or not.
If the signature is too short them i have to ask the user to put a signature again. The following is my code:
There are two classes in this.
FingerPaintActivity
public class FingerPaintActivity extends Activity implements OnClickListener{
private Button clearBtn, saveBtn;
private View myView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myView = findViewById(R.id.myView);
clearBtn = (Button) findViewById(R.id.clearBtn);
clearBtn.setOnClickListener(this);
saveBtn = (Button) findViewById(R.id.submitBtn);
saveBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == clearBtn) {
MyView.clearCanvas();
myView.invalidate();
myView.refreshDrawableState();
} else {
myView.setDrawingCacheEnabled(true);
myView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
myView.layout(0, 0, myView.getWidth(), myView.getHeight());
myView.buildDrawingCache(true);
Bitmap bm = Bitmap.createBitmap(myView.getDrawingCache());
myView.setDrawingCacheEnabled(false);
if (bm != null) {
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "screentest.jpg");
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
Log.e("ImagePath", "Image Path : " + MediaStore.Images.Media.insertImage( getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName()));
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
This is the second class:
MyView
public class MyView extends View {
// private static final float MINP = 0.25f;
// private static final float MAXP = 0.75f;
private Bitmap mBitmap;
private static Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private Paint mPaint;
public MyView(Context c) {
super(c);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(6);
mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
public static void clearCanvas() {
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
mCanvas.drawPaint(paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC));
}
}
The only problem i am facing is while saving the signature i have to check the size of bitmap or canvas or paint before saving it. i don't know which one to check for
If anyone has idea please help me out.
A simple approach would be to sum up the distances between touch coordinates, and only accept the signature if the sum is greater than a certain threshold.
So, keep a running sum of the total distance drawn in touch_move()
mTotal += Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
then later on
if(mTotal >= MINIMUM_SIGNATURE_LENGTH)
{
acceptSignature();
}
hi i need perform undo operation in paints.some one suggest use command pattern but i am not getting command pattern.is there any solution is there. help me how to do undo.
i draw paints using below code.
BookType3.class:
public class BookType3 extends Activity implements OnClickListener{
MyView myview;
int counter=0;
private Paint mBitmapPaint;
TextView t1,t2;
private Bitmap mBitmap;
public static boolean action=false;
Button back,erase,undo,save,home;
int image1,image2,image3;
private Canvas mCanvas;
RelativeLayout relative;
RelativeLayout.LayoutParams lp6,lp7;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.booktype1);
List<String> names = Arrays.asList("a","b","c");
relative=(RelativeLayout)findViewById(R.id.relative3);
myview = new MyView(this);
myview.setId(004);
lp6 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
myview.setLayoutParams(lp6);
myview.setBackgroundResource(R.drawable.writingsapce);
undo=(Button)findViewById(R.id.undobutton);
undo.setOnClickListener(this);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(4);
String s1="";
t1=(TextView)findViewById(R.id.button1);
t1.setOnClickListener(this);
t2=(TextView)findViewById(R.id.button2);
t2.setOnClickListener(this);
relative.addView(myview,lp6);
}
private Paint mPaint;
public class MyView extends View{
private Path mPath;
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
if(action)
{
invalidate();
}
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 2;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
Log.i("x",""+event.getX());
Log.i("y",""+event.getY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==t1)
{
mPaint.setColor(Color.RED);
t30.setText("A");
t31.setText("a");
t32.setText("Aa");
t30.setTextColor(Color.RED);
t31.setTextColor(Color.RED);
t32.setTextColor(Color.RED);
try{
mBitmap.eraseColor(android.graphics.Color.TRANSPARENT);
Canvas Canvas=new Canvas(mBitmap);
action=true;
myview.onDraw(Canvas);
}catch(IllegalStateException ie){
ie.printStackTrace();
}
}
if(v==t2)
{
t30.setTextColor(Color.BLUE);
t31.setTextColor(Color.BLUE);
t32.setTextColor(Color.BLUE);
mPaint.setColor(Color.BLUE);
t30.setText("B");
t31.setText("b");
t32.setText("Bb");
try{
mBitmap.eraseColor(android.graphics.Color.TRANSPARENT);
Canvas Canvas=new Canvas(mBitmap);
action=true;
myview.onDraw(Canvas);
}catch(IllegalStateException ie){
ie.printStackTrace();
}
}
if(v==undo)
{
}
}
}
Instead of the Command Pattern, I think you should use the Memento Pattern, which is designed for things like undo and redo. There are two ways to implement this pattern. Either by saving deltas, or by saving entire states. Saving states would be easiest in your situation, but it has larger memory footprint. This would involve writing a bitmap to the filesystem every time the user modifies the main bitmap. You could decide on a constant number of undo steps (e.g. 10), and then save the 10 most recent bitmaps. Saving deltas would be more complex. You would implement it by recording the touch events, color, brush, etc. of each paint action. You can then playback and/or rollback individual actions using the motion events. Saving deltas would take significantly less memory, and you would be able to store many more actions and you wouldn't have to write to the filesystem.
private Slate mSlate;
private TiledBitmapCanvas mTiledCanvas;
public void clickUndo(View unused) {
mSlate.undo();
}
public void undo() {
if (mTiledCanvas == null) {
Log.v(TAG, "undo before mTiledCanvas inited");
}
mTiledCanvas.step(-1);
invalidate();
}
I need to create a "Scratch Card" App for my final project in school and can't find the way how to implement the scratching event (How do I create background image and put Grey rectangles over it, so when I will scratch those rectangles I will see the picture under them)
The Implementation must be in Android because I don't how to develop In Objective-C yet.
I saw a reference for Objective-C Implementation, but it's no good as I don't understand it.
My Code is:
public class FingerPaint extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
MyView myView = new MyView(this);
myView.requestFocus();
myView.PaintObjectInit();
// setContentView(myView);
LinearLayout upper = (LinearLayout) findViewById(R.id.LinearLayout01);
upper.addView(myView);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
// MyImageView myImageView = new MyImageView(this);
// setContentView(myImageView);
}
}
public class MyView extends View {
private Paint mPaint;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
public MyView(Context context) {
super(context);
this.mPaint = new Paint();
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
protected void PaintObjectInit() {
mPaint.setAntiAlias(true);
mPaint.setDither(true);
//mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
//mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
try
{
//Bitmap bm1 = BitmapFactory.decodeResource(this.getResources(),R.drawable.scratch).copy(Bitmap.Config.ARGB_8888, true);;
//Bitmap bm2 = BitmapFactory.decodeResource(this.getResources(),R.drawable.main).copy(Bitmap.Config.ARGB_8888, true);;
//mBitmap = toTransparency(bm1, 0xFFAAAAAA, true, bm2);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
// mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// 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;
}
}
Please help regarding this.
I come across this problem recently and then I created a library for this so everyone can have a quick implementation of scratch view, hope this can help those who still looking for answer
https://github.com/winsontan520/Android-WScratchView
I found this library very useful.
https://github.com/sharish/ScratchView
Very easy to integrate
<com.cooltechworks.views.ScratchImageView
android:id="#+id/sample_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:src="#drawable/img_sample2"
/>
you can make "Scratch Card" application like this way. you need to follow the below code which is working code. you just need to required understand and implement your own logic.
public class MainActJava extends AppCompatActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
setContentView(new MyView(this, bitmap));
}
public class MyView extends View implements View.OnTouchListener {
private static final float TOUCH_TOLERANCE = 4;
private Paint mPaint;
private Bitmap oBitmap;
private Bitmap holder;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private float mX, mY;
public MyView(Context context) {
super(context);
}
public MyView(Context context, Bitmap bitmap) {
super(context);
setOnTouchListener(this);
this.oBitmap = bitmap;
this.mPaint = new Paint();
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
init();
}
protected void init() {
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(35);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
holder = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(holder);
}
#Override
protected void onDraw(Canvas canvas) {
onDrawing(canvas);
}
private void onDrawing(Canvas canvas) {
mCanvas.drawColor(0xFFAAAAAA);
mCanvas.drawPath(mPath, mPaint);
canvas.drawBitmap(oBitmap, getWidth()/2, getHeight()/2, mBitmapPaint);
canvas.drawBitmap(holder, 0, 0, mBitmapPaint);
}
private void touch_start(float x, float y) {
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);
mCanvas.drawPath(mPath, mPaint);
}
#Override
public boolean onTouch(View view, 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;
}
}
}
Output:
I have an activity which has an ImageView in it. What I want to do is be able to draw where the user touches that Imageview with an image from the drawable folder. I've read that the best way is to use Canvas, but I'm not sure where and how I integrate the onDraw method with the onTouchListener. This is what I have so far:
public class Main extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView)findViewById(R.id.textView);
final ImageView image = (ImageView) findViewById(R.id.imageView2);
//Bitmap
Bitmap viewBitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(viewBitmap);
image.draw(canvas);
image.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
textView.setText("Touch coordinates : " + String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
return false;
}
});
}
}
So what I want to do is when the user touches the ImageView, an image will be drawn exactly where he touched it.
You're going to want to subclass ImageView in order to override its onDraw() method. By doing so, you can also to the custom touch handling in onTouchEvent() instead of attaching a listener. This is not a complete example, but something like the following:
public class CustomImageView extends ImageView {
private ArrayList<Point) mTouches;
private Bitmap mMarker;
//Java constructor
public CustomImageView(Context context) {
super(context);
init();
}
//XML constructor
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mTouches = new ArrayList<Point>();
mMarker = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_marker_image);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//Capture a reference to each touch for drawing
if(event.getAction() == MotionEvent.ACTION_DOWN) {
mTouches.add( new Point(event.getX(), event.getY()) );
return true;
}
return super.onTouchEvent(event);
}
#Override
protected void onDraw(Canvas c) {
//Let the image be drawn first
super.onDraw(c);
//Draw your custom points here
Paint paint = new Paint();
for(Point p : mTouches) {
c.drawBitmap(mMarker, p.x, p.y, paint);
}
}
}
HTH!
I edited your class like this and it works for me
public class MyImageView extends androidx.appcompat.widget.AppCompatImageView {
private Bitmap mMarker;
private Path mPath, circlePath ;
private Paint paint, circlePaint;
private Canvas mCanvas;
//Java constructor
public MyImageView(Context context) {
super(context);
init();
}
//XML constructor
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mTouches = new ArrayList<Point>();
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(12);
mPath = new Path();
Paint mBitmapPaint = new Paint(Paint.DITHER_FLAG);
circlePaint = new Paint();
circlePath = new Path();
circlePaint.setStyle(Paint.Style.STROKE);
circlePaint.setStrokeJoin(Paint.Join.MITER);
circlePaint.setStrokeWidth(4f);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mMarker = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mMarker);
}
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;
circlePath.reset();
circlePath.addCircle(mX, mY, 30, Path.Direction.CW);
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
circlePath.reset();
// commit the path to our offscreen
mCanvas.drawPath(mPath, paint);
// 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;
}
#Override
protected void onDraw(Canvas c) {
//Let the image be drawn first
super.onDraw(c);
c.drawBitmap(mMarker, 0, 0, paint);
c.drawPath( mPath, paint);
c.drawPath( circlePath, circlePaint);
}
}