I am able to pinch zoom in/out (though its not perfect yet) i want to use 2 fingers to drag since single drag is for drawing.
is this where the ACTION_POINTER_DOWN is required?
please help me how i can have the paint app drag with 2 fingers?
Below is the code
Thank you!
public class paintView extends View {
private static final int INVALID_POINTER_ID = -1;
private float mPosX;
private float mPosY;
private int mActivePointerId = INVALID_POINTER_ID;
private final ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
Paint paint;
Path path;
public paintView(Context context) {
super(context, null, 0);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
paint = new Paint();
path = new Path();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(8f);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
path.moveTo(x,y);
return true;
}
case MotionEvent.ACTION_MOVE: {
float x = ev.getX();
float y = ev.getY();
path.lineTo(x,y);
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
}
invalidate();
return true;
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// for moving around
// 2 finger drag 할때 필요할듯
canvas.translate(mPosX, mPosY);
// for zoom
canvas.scale(mScaleFactor, mScaleFactor);
//mImage.draw(canvas);
canvas.drawPath(path, paint);
//canvas.restore();
}
// zoom in gesture
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
final float scale = detector.getScaleFactor();
mScaleFactor = Math.max(.5f, Math.min(mScaleFactor * scale, 3.0f));
if (mScaleFactor < 5f) {
// 1 Grabbing
final float centerX = detector.getFocusX();
final float centerY = detector.getFocusY();
// 2 Calculating difference
float diffX = centerX - mPosX;
float diffY = centerY - mPosY;
// 3 Scaling difference
diffX = diffX * scale - diffX;
diffY = diffY * scale - diffY;
// 4 Updating image origin
mPosX -= diffX;
mPosY -= diffY;
}
invalidate();
return true;
}
}
}
Related
Here is My code, I am trying to zoom at the specific area but my code is not working properly. I want my code to work as Autocad Canvas zoom in out can anyone know to zoom canvas just like AutoCAD canvas. I want to make the CAD application work the same as AutoCAD work please help me.
I want My code to work as zoom in-out canvas drag move canvas.
public class Custom_Canvas extends View implements View.OnTouchListener {
private static final int INVALID_POINTER_ID = -1;
private int mActivePointerId = INVALID_POINTER_ID;
Paint paint = new Paint();
// See onTouchEvent!
private float initX = 0f;
private float initY = 0f;
// x and y coord of canvas center!
private float canvasX = 0f;
private float canvasY = 0f;
private boolean drag = false;
private boolean firstdraw = true;
ScaleGestureDetector scaleGestureDetector;
private float scalefactor = 1f;
private float scalePointX, scalePointY;
float min_zoom = 0.1f;
float max_zoom = 10f;
private float lastfocusX = -1;
private float lastfocusY = -1;
#SuppressLint("ClickableViewAccessibility")
public Custom_Canvas(Context context, AttributeSet attrs){
super(context, attrs);
this.setOnTouchListener(this);
scaleGestureDetector = new ScaleGestureDetector(context,new Scalelistener());
paint.setColor(Color.WHITE);
}
#SuppressLint("ClickableViewAccessibility")
public Custom_Canvas(Context context) {
super(context);
this.setOnTouchListener(this);
paint.setColor(Color.WHITE);
scaleGestureDetector = new ScaleGestureDetector(context,new Scalelistener());
}
#SuppressLint("DrawAllocation")
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
if(firstdraw){
canvasX = getWidth()/2f;
canvasY = getHeight()/2f;
firstdraw = false;
}
canvas.scale(scalefactor,scalefactor,scalePointX,scalePointY);
canvas.translate(canvasX,canvasY);
canvas.drawCircle(0,0,20f,paint);
// canvas.drawCircle(100,100,20f,paint);
canvas.restore();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
scaleGestureDetector.onTouchEvent(event);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
float x = event.getX()/scalefactor;
float y = event.getY()/scalefactor;
// drag = true;
initX = x;
initY = y;
mActivePointerId = event.getPointerId(0);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
// case MotionEvent.ACTION_POINTER_DOWN:
final int p = event.findPointerIndex(mActivePointerId);
final float x1 = event.getX(p) / scalefactor;
final float y1 = event.getY(p) / scalefactor;
if (!scaleGestureDetector.isInProgress()) {
// if (drag) {
float dx = x1 - initX;
float dy = y1 - initY;
canvasX += dx ;
canvasY += dy ;
invalidate();
// }
}
initX = x1;
initY = y1;
break;
case MotionEvent.ACTION_POINTER_UP:
// drag = false;
final int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
initX = event.getX(newPointerIndex)/scalefactor;
initY = event.getY(newPointerIndex)/scalefactor;
mActivePointerId = event.getPointerId(newPointerIndex);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// drag = false;
mActivePointerId = INVALID_POINTER_ID;
break;
}
return true;
}
private class Scalelistener extends ScaleGestureDetector.SimpleOnScaleGestureListener{
#Override
public boolean onScale(ScaleGestureDetector detector) {
scalefactor *= detector.getScaleFactor();
scalePointX = detector.getFocusX();
scalePointY = detector.getFocusY();
Toast.makeText(getContext(), " "+scalePointX+" "+scalePointY, Toast.LENGTH_SHORT).show();
if(lastfocusX == -1){
lastfocusX = scalePointX;
}
if(lastfocusY == -1){
lastfocusY = scalePointY;
}
canvasX += (scalePointX - lastfocusX);
canvasY += (scalePointY - lastfocusY);
scalefactor = Math.max(min_zoom,Math.min(scalefactor,max_zoom));
lastfocusX = scalePointX;
lastfocusY = scalePointY;
invalidate();
return true;
}
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
lastfocusX = -1;
lastfocusY = -1;
return true;
}
#Override
public void onScaleEnd(ScaleGestureDetector detector) { }
}
I have made a custom view to paint over a bitmap. The problem is when try to paint the first touch don't show any thing and the color also changed in the next time , the second problem is that the when i save the image no thing is showed from the painted colores
Here is my code:
public class DrawView extends android.support.v7.widget.AppCompatImageView {
private ArrayList<ColouredPoint> paths ;
private ColouredPoint mPath;
private Paint mPaint;
private static final float TOUCH_TOLERANCE = 4;
boolean erase;
// Current used colour
private int mCurrColour;
public void setErase(boolean era){
erase=era;
}
public void setColor(int colour) {
mCurrColour = colour;
}
public DrawView(Context context) {
super(context);
init();
}
// XML constructor
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paths = new ArrayList<>();
mPaint = new Paint();
mPath = new ColouredPoint(mCurrColour);
mPaint.setColor(mCurrColour);
mPaint.setDither(true);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(15);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
}
private float mX, mY;
#Override
public boolean onTouchEvent(MotionEvent event) {
// Capture a reference to each touch for drawing
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
break;
case MotionEvent.ACTION_MOVE:
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;}
break;
case MotionEvent.ACTION_UP:
mPath.lineTo(mX, mY);
mPath = new ColouredPoint(mCurrColour);
paths.add(mPath);
break;
}
return super.onTouchEvent(event);
}
#Override
protected void onDraw(Canvas c) {
// Let the image be drawn first
super.onDraw(c);
// Draw your custom points here
if(!erase){
for (ColouredPoint i:paths) {
mPaint.setColor(i.colour);
c.drawPath(i, mPaint);}}
else if (paths.size()>0){
paths.remove(paths.size()-1);
} else {
Toast.makeText(getContext(), "Undo unknown", Toast.LENGTH_SHORT)
.show();}}
/**
* Class to store the coordinate and the colour of the point.
*/
private class ColouredPoint extends Path{
int colour;
public ColouredPoint(int colour) {
this.colour = colour;
}
}
}
how to fix this ?
Heres my code to drawing with fingers paint line and draw circle. I want to know how to find line's length and want to draw circle with radius line's length.
How can I do this?
And where to put this line?
circlePath.addCircle(mX, mY, "line's length", Path.Direction.CW);
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Paint mPaint;
float Mx1,My1;
float x,y;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
MyView view1 =new MyView(this);
view1.setBackgroundResource(R.color.colorPrimary);
setContentView(view1);
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(10);
}
public class MyView extends View {
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private Paint circlePaint;
private Path circlePath;
public MyView(Context c) {
super(c);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
circlePaint = new Paint();
circlePath = new Path();
circlePaint.setAntiAlias(true);
circlePaint.setColor(Color.BLUE);
circlePaint.setStyle(Paint.Style.STROKE);
circlePaint.setStrokeJoin(Paint.Join.MITER);
circlePaint.setStrokeWidth(8f);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
//canvas.drawLine(mX, mY, Mx1, My1, mPaint);
//canvas.drawLine(mX, mY, x, y, mPaint);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
canvas.drawPath(circlePath, circlePaint);
}
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, Math.abs(mX - mY), Path.Direction.CW);
}
private void touch_up() {
mPath.lineTo(mX, mY);
//circlePath.reset();
// 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);
circlePath.addCircle(mX, mY, x, Path.Direction.CW);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
//Mx1=(int) event.getX();
//My1= (int) event.getY();
invalidate();
break;
}
return true;
}
}
}
I solved.
float first_x, first_y, last_x, last_y, line_lenght;
#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);
first_x = x;
first_y = y;
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
last_x = x;
last_y = y;
line_lenght = (float) Math.pow(Math.abs(first_x-last_x),2) + (float) Math.pow(Math.abs(first_y-last_y),2);
line_lenght = (float) Math.sqrt(line_lenght);
circlePath.reset();
circlePath.addCircle(mX, mY, line_lenght, Path.Direction.CW);
invalidate();
break;
case MotionEvent.ACTION_UP:
last_x = x;
last_y = y;
line_lenght = (float) Math.pow(Math.abs(first_x-last_x),2) + (float) Math.pow(Math.abs(first_y-last_y),2);
line_lenght = (float) Math.sqrt(line_lenght);
circlePath.reset();
circlePath.addCircle(mX, mY, line_lenght, Path.Direction.CW);
touch_up();
//Mx1=(int) event.getX();
//My1= (int) event.getY();
invalidate();
break;
}
return true;
}
In my app, the customer has to sign at the end of the process. Below code is how I manage to make it work.
DrawView
public class DrawView
extends View {
private static final float STROKE_WIDTH = 5f;
/** Need to track this so the dirty region can accommodate the stroke. **/
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
/** Optimizes painting by invalidating the smallest possible area. */
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();
public DrawView(Context context) {
super(context);
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}
/** Erases the signature. */
public void clear() {
path.reset();
// Repaints the entire view.
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
// There is no end point yet, so don't waste cycles invalidating.
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
// Start tracking the dirty region.
resetDirtyRect(eventX, eventY);
// When the hardware tracks events faster than they are delivered,
// the
// event will contain a history of those skipped points.
int historySize = event.getHistorySize();
//Logger.debug("historySize : " + historySize);
for (int i = 0; i < historySize; i++) {
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;
default:
//Logger.debug("Ignored touch event: " + event.toString());
return false;
}
// Include half the stroke width to avoid clipping.
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH), (int) (dirtyRect.top - HALF_STROKE_WIDTH), (int) (dirtyRect.right + HALF_STROKE_WIDTH), (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}
/** Called when replaying history to ensure the dirty region includes all
* points. */
private void expandDirtyRect(float historicalX, float historicalY) {
if (historicalX < dirtyRect.left) {
dirtyRect.left = historicalX;
} else if (historicalX > dirtyRect.right) {
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top) {
dirtyRect.top = historicalY;
} else if (historicalY > dirtyRect.bottom) {
dirtyRect.bottom = historicalY;
}
}
/** Resets the dirty region when the motion event occurs. */
private void resetDirtyRect(float eventX, float eventY) {
// The lastTouchX and lastTouchY were set when the ACTION_DOWN
// motion event occurred.
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
and I use FrameLayout to show in the app like this.
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
drawView = new DrawView(this);
drawView.requestFocus();
preview.addView(drawView);
It is working fine. My question is how do I do validation for this. Let's say I throw a pop up saying customer hasn't signed yet. please advice.
I have a simple Custom View and Scale Gesture detector implemented for the Pinch (zoom) gesture, just like this (found it on StackOverflow too):
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
public class MyImageView extends View {
private static final int INVALID_POINTER_ID = -1;
private Drawable mImage;
private float mPosX;
private float mPosY;
private float mLastTouchX;
private float mLastTouchY;
private int mActivePointerId = INVALID_POINTER_ID;
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
public MyImageView(Context context) {
this(context, null, 0);
mImage=act.getResources().getDrawable(context.getResources().getIdentifier("imagename", "drawable", "packagename"));
mImage.setBounds(0, 0, mImage.getIntrinsicWidth(), mImage.getIntrinsicHeight());
}
public MyImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
// Only move if the ScaleGestureDetector isn't processing a gesture.
if (!mScaleDetector.isInProgress()) {
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
invalidate();
}
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK)
>> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
}
break;
}
}
return true;
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
Log.d("DEBUG", "X: "+mPosX+" Y: "+mPosY);
canvas.translate(mPosX, mPosY);
canvas.scale(mScaleFactor, mScaleFactor);
mImage.draw(canvas);
canvas.restore();
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
invalidate();
return true;
}
}
}
Then, when the View is Zoomed, I want to limit the Translation to go only to the boundaries of the Image that is being drawn in onDraw().
I thought I'll have that controled with Canvas.getClipBounds() just to see what's the zoomed image offset off of the Viewport, but then I cannot figure out how to control that.
To be more precise, I want my View not to translate the Image more than the 0 Left and 0 Top points of the View.
Thanks!
Change
canvas.translate(mPosX, mPosY);
To
if((mPosX<0)&&(mImage.getIntrinsicWidth()<canvas.getWidth()))
mPosX = 0;
if((mPosY<0)&&(mImage.getIntrinsicHeight()<canvas.getHeight()))
mPosY = 0;
canvas.translate(mPosX, mPosY);