Wrong scale position after applying zoom effect on Android canvas - android

First of all this is a follow up question originally asked here, Pan, Zoom and Scale a custom View for Canvas drawing in Android
Since there was no answer yet, I finally solved my issue using the android-gesture-detectors
After applying the zoom/scale gesture I found that, the canvas drawing coordinates are still pointing to the old position (before applying the zoom) and not drawing on the exact same touch coordinates. Basically, I can't get the correct canvas coordinates after scaling or dragging the canvas.
Before zooming,
After zooming out the touch points are drawing on the previous location. I want it to draw on the current touch location,
Sample code,
public class DrawingView extends View {
private void setupDrawing() {
mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
mgd = new MoveGestureDetector(ctx, mgl);
sgd = new ScaleGestureDetector(ctx, sgl);
rgd = new RotateGestureDetector(ctx, rgl);
}
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, 5.0f));
invalidate();
return true;
}
}
MoveGestureDetector.SimpleOnMoveGestureListener mgl = new MoveGestureDetector.SimpleOnMoveGestureListener() {
#Override
public boolean onMove(MoveGestureDetector detector) {
PointF delta = detector.getFocusDelta();
matrix.postTranslate(delta.x, delta.y);
invalidate();
return true;
}
};
ScaleGestureDetector.SimpleOnScaleGestureListener sgl = new ScaleGestureDetector.SimpleOnScaleGestureListener() {
#Override
public boolean onScale(ScaleGestureDetector detector) {
float scale = detector.getScaleFactor();
matrix.postScale(scale, scale, detector.getFocusX(), detector.getFocusY());
invalidate();
return true;
}
};
RotateGestureDetector.SimpleOnRotateGestureListener rgl = new RotateGestureDetector.SimpleOnRotateGestureListener() {
#Override
public boolean onRotate(RotateGestureDetector detector) {
matrix.postRotate(-detector.getRotationDegreesDelta(), detector.getFocusX(), detector.getFocusY());
invalidate();
return true;
}
};
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
//view given size
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}
private void touch_start(float x, float y) {
undonePaths.clear();
drawPath.reset();
drawPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y, float x2, float y2) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
/* QUad to curves using a quadratic line (basically an ellipse of some sort).
LineTo is a straight line. QuadTo will smooth out jaggedies where they turn.
*/
drawPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
drawPath.lineTo(mX, mY);
// commit the path to our offscreen
drawCanvas.drawPath(drawPath, drawPaint);
// kill this so we don't double draw
paths.add(drawPath);
drawPath = new Path();
drawPath.reset();
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (isZoomable) {
mgd.onTouchEvent(event);
sgd.onTouchEvent(event);
rgd.onTouchEvent(event);
}
if (!isTouchable) {
return super.onTouchEvent(event);
} else {
//detect user touch
float x = event.getX();
float y = event.getY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (!isZoomable) {
touch_start(x, y);
}
invalidate();
break;
case MotionEvent.ACTION_MOVE:
if (!isZoomable) {
//mPositions.add(new Vector2(x - mBitmapBrushDimensions.x / 2, y - mBitmapBrushDimensions.y / 2));
if (isCustomBrush && mBitmapBrushDimensions != null) {
mPositions = new Vector2(x - mBitmapBrushDimensions.x / 2, y - mBitmapBrushDimensions.y / 2);
touch_move(x, y, x - mBitmapBrushDimensions.x / 2, y - mBitmapBrushDimensions.y / 2);
} else {
touch_move(x, y, 0, 0);
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
if (!isZoomable) {
touch_up();
}
invalidate();
break;
}
mScaleDetector.onTouchEvent(event);
return true;
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.setMatrix(matrix);
for (Path p : paths) {
canvas.drawPath(p, drawPaint);
drawPaint.setColor(selectedColor);
drawPaint.setStrokeWidth(brushSize);
canvas.drawPath(drawPath, drawPaint);
}
canvas.restore();
}
}
PS: MoveGestureDetector(), ScaleGestureDetector() & RotateGestureDetector() are custom classes inherited from android-gesture-detectors

Here's what I did. Basically, you have to find the difference between the "old" and new points. Skip to the bottom for the important lines...
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
float xDiff = initialFocalPoints[0] - currentFocalPoints[0];
float yDiff = initialFocalPoints[1] - currentFocalPoints[1];
transformMatrix.setScale(scaleFactor, scaleFactor,
currentFocalPoints[0], currentFocalPoints[1]);
transformMatrix.postTranslate(xDiff, yDiff);
child.setImageMatrix(transformMatrix);
return true;
}
#Override
public boolean onScaleBegin(ScaleGestureDetector detector){
float startX = detector.getFocusX() + getScrollX();
float startY = detector.getFocusY() + getScrollY();
initialFocalPoints = new float[]{startX, startY};
if(transformMatrix.invert(inverseTransformMatrix))
inverseTransformMatrix.mapPoints(currentFocalPoints, initialFocalPoints);
return true;
}
The lines that made the difference were the following:
float xDiff = initialFocalPoints[0] - currentFocalPoints[0];
float yDiff = initialFocalPoints[1] - currentFocalPoints[1];
transformMatrix.postTranslate(xDiff, yDiff);
The answer was as simple as figuring out the difference between the two points and translating the imageview everytime the image is scaled.

To apply any transformation you have to understand the rules of mathematics. It works both for 2dim and 3 dimensions graphics.
That is, if you work with translation (T), rotation (R), scale (S) matrices to apply any transformation, you have scale object at first (multiply coordinates xyz by this matrix S) then rotate (mult. by R) then shift the object by T.
So, you apply rotation over some point you have to move the object to zero and scale then return to base point.
That is namely in your case, before applying scale, you have to shift (decrease) all coordinates by touch position then apply scale matrix by multiplication then shift by increasing all positions by this touch against.

Related

Path draw in opposite direction at canvas when rotate android

Hi i am erasing bitmap that is draw at canvas with touch (fingers) that is working fine the problem i am facing is after rotate bitmap at canvas paths draw in opposition direction mean bitmap erase in opposition direction of my finger touch .
DrawingPane.class
public class DrawingPanel extends ImageView implements OnTouchListener {
private Matrix mMatrix = new Matrix();
private float mScaleFactor = 1f;
private float mRotationDegrees = 0.f;
private float mFocusX = 0.f;
private float mFocusY = 0.f;
private int mAlpha = 255;
private int mImageHeight, mImageWidth;
private ScaleGestureDetector mScaleDetector;
private RotateGestureDetector mRotateDetector;
private MoveGestureDetector mMoveDetector;
private ShoveGestureDetector mShoveDetector;
private boolean isMoving=false;
EditPhotoActivity editActivity;
Bitmap overlayDefault;
Bitmap overlay;
Bitmap bmp,bmp2;
Paint pTouch;
int whichTabSelected=0;
private Path mPath;
Display display ;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Float> xlist = new ArrayList<Float>();
private ArrayList<Float> ylist = new ArrayList<Float>();
#SuppressLint("NewApi")
public DrawingPanel(Context context, int colorPaint,Bitmap bmp) {
super(context);
if (Build.VERSION.SDK_INT >= 11) {
setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
display = ((Activity)context).getWindowManager().getDefaultDisplay();
mFocusX = display.getWidth()/2f;
mFocusY = display.getHeight()/2f;
try {
overlayDefault=bmp;
overlay=bmp;
overlay=overlay.copy(Config.ARGB_8888, true);
overlay.setHasAlpha(true);
} catch (Exception e) {
e.printStackTrace();
}
mImageHeight = getHeight();
mImageWidth = getWidth();
// Setup Gesture Detectors
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
mRotateDetector = new RotateGestureDetector(context, new RotateListener());
mMoveDetector = new MoveGestureDetector(context, new MoveListener());
mShoveDetector = new ShoveGestureDetector(context, new ShoveListener());
pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
pTouch.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
pTouch.setColor(Color.TRANSPARENT);
//pTouch.setMaskFilter(new BlurMaskFilter(30, Blur.SOLID));
pTouch.setStyle(Paint.Style.STROKE);
pTouch.setStrokeJoin(Paint.Join.ROUND);
pTouch.setStrokeCap(Paint.Cap.ROUND);
pTouch.setStrokeWidth(50);
pTouch.setAntiAlias(true);
setFocusable(true);
setFocusableInTouchMode(true);
mPath = new Path();
paths.add(mPath);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mImageHeight=getHeight();
mImageWidth=getWidth();
bmp = Bitmap.createScaledBitmap(overlay, w, h, false);
bmp2 = Bitmap.createScaledBitmap(overlayDefault, w, h, false);
overlay = bmp.copy(Config.ARGB_8888, true);
overlayDefault = bmp2.copy(Config.ARGB_8888, true);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
#Override
protected void onDraw(Canvas canvas) {
// mCanvas.drawBitmap(overlayDefault,0, 0, null); //exclude this line to show all as you draw
// mCanvas.drawCircle(X, Y, 80, pTouch);
//draw the overlay over the background
float scaledImageCenterX = (mImageWidth*mScaleFactor)/2;
float scaledImageCenterY = (mImageHeight*mScaleFactor)/2;
mMatrix.reset();
mMatrix.postScale(mScaleFactor, mScaleFactor);
mMatrix.postRotate(mRotationDegrees, scaledImageCenterX, scaledImageCenterY);
if(isMoving)
{
mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY);
}
else
{
mMatrix.postTranslate(0,0);
}
canvas.setMatrix(mMatrix);
canvas.drawBitmap(overlay,0,0, null);
for (Path p : paths) {
canvas.drawPath(p, pTouch);
}
super.onDraw(canvas);
}
public Bitmap getBitmap(){
Bitmap b = Bitmap.createScaledBitmap(overlay,display.getWidth() ,display.getWidth(), false);
overlay = b.copy(Config.ARGB_8888, true);
return overlay;
}
public void setBitmap(Bitmap bmp1){
overlay = bmp1;
invalidate();
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 0;
public void touch_start(float x, float y) {
if(xlist.size()>0 && ylist.size()>0){
xlist.clear();
ylist.clear();
}
xlist.add(x);
ylist.add(y);
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
mPath.transform(mMatrix, mPath);
invalidate();
}
public 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;
mPath.transform(mMatrix, mPath);
}
xlist.add(x);
ylist.add(y);
invalidate();
}
public void touch_up() {
mPath.lineTo(mX, mY);
mPath = new Path();
mPath.transform(mMatrix, mPath);
paths.add(mPath);
invalidate();
}
public void OnTouchParent(MotionEvent event){
mScaleDetector.onTouchEvent(event);
mRotateDetector.onTouchEvent(event);
mMoveDetector.onTouchEvent(event);
mShoveDetector.onTouchEvent(event);
float scaledImageCenterX = (mImageWidth*mScaleFactor)/2;
float scaledImageCenterY = (mImageHeight*mScaleFactor)/2;
mMatrix.reset();
mMatrix.postScale(mScaleFactor, mScaleFactor);
mMatrix.postRotate(mRotationDegrees, scaledImageCenterX, scaledImageCenterY);
mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY);
float x = event.getX();
float y = event.getY();
/*switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(whichTabSelected==Constant.ERASE)
{
touch_start(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_MOVE:
if(whichTabSelected==Constant.ERASE)
{
touch_move(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if(whichTabSelected==Constant.ERASE)
{
touch_up();
invalidate();
}
break;
}
if(whichTabSelected==Constant.ERASE)
{
return true;
}
else
{
return false;
}*/
invalidate();
}
#Override
public boolean onTouch(View arg0, MotionEvent event) {
if(getTabMode()==Constant.PANZOOM)
{
mScaleDetector.onTouchEvent(event);
mRotateDetector.onTouchEvent(event);
mMoveDetector.onTouchEvent(event);
mShoveDetector.onTouchEvent(event);
float scaledImageCenterX = (mImageWidth*mScaleFactor)/2;
float scaledImageCenterY = (mImageHeight*mScaleFactor)/2;
}
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(getTabMode()==Constant.ERASE)
{
touch_start(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_MOVE:
if(getTabMode()==Constant.ERASE)
{
touch_move(x, y);
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if(getTabMode()==Constant.ERASE)
{
touch_up();
invalidate();
}
break;
}
invalidate();
return true;
}
public void setBottomTabMode(int mode)
{
whichTabSelected=mode;
}
public int getTabMode()
{
return whichTabSelected;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor(); // scale change since previous event
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
return true;
}
}
private class RotateListener extends RotateGestureDetector.SimpleOnRotateGestureListener {
#Override
public boolean onRotate(RotateGestureDetector detector) {
mRotationDegrees -= detector.getRotationDegreesDelta();
return true;
}
}
private class MoveListener extends MoveGestureDetector.SimpleOnMoveGestureListener {
#Override
public boolean onMove(MoveGestureDetector detector) {
PointF d = detector.getFocusDelta();
mFocusX += d.x;
mFocusY += d.y;
isMoving=true;
// mFocusX = detector.getFocusX();
// mFocusY = detector.getFocusY();
return true;
}
}
private class ShoveListener extends ShoveGestureDetector.SimpleOnShoveGestureListener {
#Override
public boolean onShove(ShoveGestureDetector detector) {
mAlpha += detector.getShovePixelsDelta();
if (mAlpha > 255)
mAlpha = 255;
else if (mAlpha < 0)
mAlpha = 0;
return true;
}
}
}
I fixed my problem. Actually when i rotate canvas the event.getX() and event.getY() were not map to current rotation of matrix so by adding this line in mMatrix.invert(tempMatrix); in OnDraw() and also map current x,y in OnTouch() by adding this in OnTouch() method .
float[] coords = new float[] { event.getX(), event.getY() };
tempMatrix.mapPoints(coords);
float x = coords[0];//event.getX();
float y = coords[1];//event.getY();
its working fine .
This effect is happening because you are applying the matrix twice to paths.
Once at touch_start/touch_move by doing mPath.transform(mMatrix, mPath);.
And then again at onDraw(Canvas canvas) by canvas.setMatrix(mMatrix); and then canvas.drawPath(p, pTouch);.
To fix, try to remove the mPath.transform(mMatrix, mPath); from touch_start/touch_move.
Also, I do not know if it is a good practice to set the matrix directly to the canvas. Instead of canvas.setMatrix(mMatrix);, I would prefer to do the following:
canvas.save();
canvas.concat(mMatrix);
//write the code....
canvas.restore();

Zoomable canvas (SurfaceView)

During the past weeks I was looking for appropriate source code showing how to enable zoom and pan functionality on a custom view. All solutions that I found had some problems. For example the movement/zoom was not smooth enough or the view jumped around when releasing one finger after a scaling (two-finger) operation. So I came up with a modified solution that I want to share with you. Suggestions and enhancements are welcomed.
What’s different?
It is bad practice to calculate the difference (distance vector) on any interaction (pan, zoom) between each single events and use it to set new values. If you do so, the action does not look smooth and the view might flicker (jump around in some pixels). A better approach is to remember values when the action starts (onScaleBegin, touch-down) and calculate distances for each event in comparison to those start values.
You could handle finger indices in onTouchEvent to better distinguish between pan/move and zoom/scale interaction.
public class CanvasView extends SurfaceView implements SurfaceHolder.Callback {
final static String TAG = "CanvasView";
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
ScaleGestureDetector mScaleDetector;
InteractionMode mode;
Matrix mMatrix = new Matrix();
float mScaleFactor = 1.f;
float mTouchX;
float mTouchY;
float mTouchBackupX;
float mTouchBackupY;
float mTouchDownX;
float mTouchDownY;
Rect boundingBox = new Rect();
public CanvasView(Context context) {
super(context);
// we need to get a call for onSurfaceCreated
SurfaceHolder sh = this.getHolder();
sh.addCallback(this);
// for zooming (scaling) the view with two fingers
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
boundingBox.set(0, 0, 1024, 768);
paint.setColor(Color.GREEN);
paint.setStyle(Style.STROKE);
setFocusable(true);
// initial center/touch point of the view (otherwise the view would jump
// around on first pan/move touch
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
mTouchX = metrics.widthPixels / 2;
mTouchY = metrics.heightPixels / 2;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
if (!this.mScaleDetector.isInProgress()) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
// similar to ScaleListener.onScaleEnd (as long as we don't
// handle indices of touch events)
mode = InteractionMode.None;
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "Touch down event");
mTouchDownX = event.getX();
mTouchDownY = event.getY();
mTouchBackupX = mTouchX;
mTouchBackupY = mTouchY;
// pan/move started
mode = InteractionMode.Pan;
break;
case MotionEvent.ACTION_MOVE:
// make sure we don't handle the last move event when the first
// finger is still down and the second finger is lifted up
// already after a zoom/scale interaction. see
// ScaleListener.onScaleEnd
if (mode == InteractionMode.Pan) {
Log.d(TAG, "Touch move event");
// get current location
final float x = event.getX();
final float y = event.getY();
// get distance vector from where the finger touched down to
// current location
final float diffX = x - mTouchDownX;
final float diffY = y - mTouchDownY;
mTouchX = mTouchBackupX + diffX;
mTouchY = mTouchBackupY + diffY;
CalculateMatrix(true);
}
break;
}
}
return true;
}
#Override
public void onDraw(Canvas canvas) {
int saveCount = canvas.getSaveCount();
canvas.save();
canvas.concat(mMatrix);
canvas.drawColor(Color.BLACK);
canvas.drawRect(boundingBox, paint);
canvas.restoreToCount(saveCount);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
// otherwise onDraw(Canvas) won't be called
this.setWillNotDraw(false);
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
void CalculateMatrix(boolean invalidate) {
float sizeX = this.getWidth() / 2;
float sizeY = this.getHeight() / 2;
mMatrix.reset();
// move the view so that it's center point is located in 0,0
mMatrix.postTranslate(-sizeX, -sizeY);
// scale the view
mMatrix.postScale(mScaleFactor, mScaleFactor);
// re-move the view to it's desired location
mMatrix.postTranslate(mTouchX, mTouchY);
if (invalidate)
invalidate(); // re-draw
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
float mFocusStartX;
float mFocusStartY;
float mZoomBackupX;
float mZoomBackupY;
public ScaleListener() {
}
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = InteractionMode.Zoom;
mFocusStartX = detector.getFocusX();
mFocusStartY = detector.getFocusY();
mZoomBackupX = mTouchX;
mZoomBackupY = mTouchY;
return super.onScaleBegin(detector);
}
#Override
public void onScaleEnd(ScaleGestureDetector detector) {
mode = InteractionMode.None;
super.onScaleEnd(detector);
}
#Override
public boolean onScale(ScaleGestureDetector detector) {
if (mode != InteractionMode.Zoom)
return true;
Log.d(TAG, "Touch scale event");
// get current scale and fix its value
float scale = detector.getScaleFactor();
mScaleFactor *= scale;
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
// get current focal point between both fingers (changes due to
// movement)
float focusX = detector.getFocusX();
float focusY = detector.getFocusY();
// get distance vector from initial event (onScaleBegin) to current
float diffX = focusX - mFocusStartX;
float diffY = focusY - mFocusStartY;
// scale the distance vector accordingly
diffX *= scale;
diffY *= scale;
// set new touch position
mTouchX = mZoomBackupX + diffX;
mTouchY = mZoomBackupY + diffY;
CalculateMatrix(true);
return true;
}
}
}

Implementing pinch zoom and drag using Android's build in gesture listener and scale listener

I am trying to implement pinch zoom and drag using Android's gesture listener and scale listener. The problem is that when I perform pinch zoom, the image (which I am trying to zoom) bounces to a particular location. Also the zoom position is not centered.
The following code demonstrates what I am trying to achieve. Any idea why the image is jumping (and how to correct it) ?
public class CustomView extends View {
Bitmap image;
int screenHeight;
int screenWidth;
Paint paint;
GestureDetector gestures;
ScaleGestureDetector scaleGesture;
float scale = 1.0f;
float horizontalOffset, verticalOffset;
int NORMAL = 0;
int ZOOM = 1;
int DRAG = 2;
boolean isScaling = false;
float touchX, touchY;
int mode = NORMAL;
public CustomView(Context context) {
super(context);
//initializing variables
image = BitmapFactory.decodeResource(getResources(),
R.drawable.image_name);
//This is a full screen view
screenWidth = getResources().getDisplayMetrics().widthPixels;
screenHeight = getResources().getDisplayMetrics().heightPixels;
paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
paint.setColor(Color.WHITE);
scaleGesture = new ScaleGestureDetector(getContext(),
new ScaleListener());
gestures = new GestureDetector(getContext(), new GestureListener());
mode = NORMAL;
initialize();
}
//Best fit image display on canvas
private void initialize() {
float imgPartRatio = image.getWidth() / (float) image.getHeight();
float screenRatio = (float) screenWidth / (float) screenHeight;
if (screenRatio > imgPartRatio) {
scale = ((float) screenHeight) / (float) (image.getHeight()); // fit height
horizontalOffset = ((float) screenWidth - scale
* (float) (image.getWidth())) / 2.0f;
verticalOffset = 0;
} else {
scale = ((float) screenWidth) / (float) (image.getWidth()); // fit width
horizontalOffset = 0;
verticalOffset = ((float) screenHeight - scale
* (float) (image.getHeight())) / 2.0f;
}
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.drawColor(0, Mode.CLEAR);
canvas.drawColor(Color.WHITE);
if(mode == DRAG || mode == NORMAL) {
//This works perfectly as expected
canvas.translate(horizontalOffset, verticalOffset);
canvas.scale(scale, scale);
canvas.drawBitmap(image, getMatrix(), paint);
}
else if (mode == ZOOM) {
//PROBLEM AREA - when applying pinch zoom,
//the image jumps to a position abruptly
canvas.scale(scale, scale, touchX, touchY);
canvas.drawBitmap(image, getMatrix(), paint);
}
canvas.restore();
}
public class ScaleListener implements OnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
float scaleFactorNew = detector.getScaleFactor();
if (detector.isInProgress()) {
touchX = detector.getFocusX();
touchY = detector.getFocusY();
scale *= scaleFactorNew;
invalidate(0, 0, screenWidth, screenHeight);
}
return true;
}
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
isScaling = true;
mode=ZOOM;
return true;
}
#Override
public void onScaleEnd(ScaleGestureDetector detector) {
mode = NORMAL;
isScaling = false;
}
}
public class GestureListener implements GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener {
#Override
public boolean onDown(MotionEvent e) {
isScaling = false;
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (!isScaling) {
mode = DRAG;
isScaling = false;
horizontalOffset -= distanceX;
verticalOffset -= distanceY;
invalidate(0, 0, screenWidth, screenHeight);
} else {
mode = ZOOM;
isScaling = true;
}
return true;
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
scaleGesture.onTouchEvent(event);
gestures.onTouchEvent(event);
return true;
}
}
Thanks in advance.
I have implemented this behaviour, and I used a matrix to handle all the zooming and scrolling (and rotation, in my case). It makes for neat code and works like clockwork.
Store a Matrix as a class member:
Matrix drawMatrix;
Edit: Store old focus point, used to get the focus shift during scaling.
float lastFocusX;
float lastFocusY;
Edit: Set lastFocus variables in onScaleBegin
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
lastFocusX = detector.getFocusX();
lastFocusY = detector.getFocusY();
return true;
}
Replace your onScale:
#Override
public boolean onScale(ScaleGestureDetector detector) {
Matrix transformationMatrix = new Matrix();
float focusX = detector.getFocusX();
float focusY = detector.getFocusY();
//Zoom focus is where the fingers are centered,
transformationMatrix.postTranslate(-focusX, -focusY);
transformationMatrix.postScale(detector.getScaleFactor(), detector.getScaleFactor());
/* Adding focus shift to allow for scrolling with two pointers down. Remove it to skip this functionality. This could be done in fewer lines, but for clarity I do it this way here */
//Edited after comment by chochim
float focusShiftX = focusX - lastFocusX;
float focusShiftY = focusY - lastFocusY;
transformationMatrix.postTranslate(focusX + focusShiftX, focusY + focusShiftY);
drawMatrix.postConcat(transformationMatrix);
lastFocusX = focusX;
lastFocusY = focusY;
invalidate();
return true;
}
Similarly in onScroll:
#Override
public boolean onScroll(MotionEvent downEvent, MotionEvent currentEvent,
float distanceX, float distanceY) {
drawMatrix.postTranslate(-distanceX, -distanceY);
invalidate();
return true;
}
in onDraw; Draw with your drawMatrix:
canvas.drawBitmap(image, drawMatrix, paint);
Happy coding!

how to draw a line on imageview in android

In my app I want to draw a line on imageview.I want to write a line with finger when i touch it.This is my requirement.For that i googled alot And fallow the bellow link:
How to draw a Line in ImageView on Android?.
In my activity i have created the object to MyImageView class and in my OnTouchListener override onTouch() method and in MotionEvent.ACTION_DOWN: switch case i have written update() method.And i am getting this error:" The method update() is undefined for the type new View.OnTouchListener(){}".So please any one suggest me to how to do this.Thanks for any help inadvance.
This is my code:
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
ImageView view = (ImageView) v;
view.setScaleType(ImageView.ScaleType.MATRIX);
float scale;
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN: // first finger down only
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
og.d(TAG, "mode=DRAG"); // write to LogCat
mode1 = DRAG1;
if(checkPencil){
//update();
}
break;
case MotionEvent.ACTION_UP: // first finger lifted
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
mode1 = NONE1;
Log.d(TAG, "mode1=NONE1");
break;
case MotionEvent.ACTION_MOVE:
if (mode1 == DRAG1)
{
if(check){ matrix.set(savedMatrix); matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); // create the transformation in the matrix of points
}
}
else if (mode1 == ZOOM1)
{
if(check){
Log.e("if elseeeeeee","dfgrtgytey");
// pinch zooming
float newDist = spacing(event);
Log.d(TAG, "newDist=" + newDist);
if (newDist > 5f)
{
matrix.set(savedMatrix);
scale = newDist / oldDist; // setting the scaling of the
// matrix...if scale > 1 means
// zoom in...if scale < 1 means
// zoom out
matrix.postScale(scale, scale, mid.x, mid.y);
}
// its for rotation..
if (lastEvent!=null){
newRot = rotation(event);
//if (Constant.TRACE) Log.d("Degreeeeeeeeeee", "newRot="+(newRot));
float r = newRot-d; matrix.postRotate(r, view.getMeasuredWidth()/2, view.getMeasuredHeight()/2);
}
}
}
break;
//rotation..
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) { savedMatrix.set(matrix);
midPoint(mid, event);
mode1 = ZOOM1;
Log.d(TAG, "mode=ZOOM")
}
lastEvent = new float[4];
lastEvent[0] = event.getX(0);
lastEvent[1] = event.getX(1);
lastEvent[2] = event.getY(0);
lastEvent[3] = event.getY(1);
d = rotation(event);
break;
}//switch
view.setImageMatrix(matrix); // display the transformation on screen
return true; // indicate event was handled
}
});
In my app drag the image,rotate the image and zoom the image everything is working fine.And my requirement is when i click the button drawing functionality will be working.that is the reason i have written the update method in this block:"if(checkPencil){
//update();
}.But it is not working.
Canvas c = null;
c = mSurfaceHolder.lockCanvas();
imageview.line(canvas);
mSurfaceHolder.unlockCanvasAndPost(c);
public void line(Canvas draw){
// set the layout parameters
// get the background image as ImageView
// Use the gesture Overlay concept.
}
The link you posted should work. Instead of using the stock image view, create a class which extends it. The imageview you extend will support a method called addLine which will add the line in an arraylist and override the onDraw method to draw the lines in the arraylist
public class Line{
int x1,y2, x2,y2;
Paint p;
public Line(int x1, y1, x2, y2){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
p= new Paint(Paint.ANTI_ALIAS_FLAG);
}
public void draw(Canvas c){
c.drawLine(x1, y1, x2, y2, p);
}
}
public class MyImageView extends ImageView{
ArrayList<Line> lines;
public void addLine(int x1, int y1, int x2, int y2){
lines.add(new Line(x1,y1,x2,y2));
//this.invalidate(); //queue a call to the onDraw method
}
public MyImageView(Context context) {
super(context);
lines = new ArrayList<Line>();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for(Line l : lines){
l.draw(canvas);
}
}
}
hye friends
Simple Line Drawing with canvas:-
public class MainActivity extends Activity {
private RelativeLayout relativelayout;
private Paint mPaint, mBitmapPaint;
private MyView mView;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativelayout = (RelativeLayout) findViewById(R.id.item);
DisplayMetrics metrics = getBaseContext().getResources().getDisplayMetrics();
int w = metrics.widthPixels;
int h = metrics.heightPixels;
System.out.println(" width " + w);
System.out.println(" height " + h);
mView = new MyView(this, w, h);
mView.setDrawingCacheEnabled(true);
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(5);
relativelayout.addView(mView);
}
public class MyView extends View {
public MyView(Context c, int w, int h) {
super(c);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mBitmapPaint
.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
}
#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(Color.TRANSPARENT);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 5;
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);
mCanvas.drawPath(mPath, mPaint);
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;
}
}
}

Android canvas get cleaned when using many path and paint object

Can someone explain me why on earth this piece of code does not draw every object?
public class A extends View {
private Paint paint = new Paint();
private Path path = new Path();
ArrayList<Pair<Path, Paint>> paths = new ArrayList<Pair<Path, Paint>>();
public A(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
for (Pair<Path, Paint> p : paths) {
canvas.drawPath(p.first, p.second);
}
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(3f);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
int color = Color.rgb(new Random().nextInt(255),
new Random().nextInt(255),
new Random().nextInt(255));
paint.setColor(color);
path.reset(); //new stroke, get old one erased
int historySize = event.getHistorySize();
for (int i = 0; i > historySize; i++) {
path.moveTo(eventX, eventY);
}
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
return true;
case MotionEvent.ACTION_UP:
path.lineTo(eventX, eventY);
// End of stroke, add this to the collection
paths.add(new Pair<Path, Paint>(path, paint));
break;
default:
break;
}
// Schedules a repaint.
invalidate();
return true;
}
}
I'm catching every strokes with the onTouchEvent and i create different path/paint ojects stored in a Pair one. Sadly in my OnDraw when I try to draw them all it fails ..
I've read some topic without finding right answer. Each time some people recommend to create and work in a bitmap and draw it to the screen but i'd like to avoid this solution.
Thank's for your help !
The problem is that you always use the same Path and Paint object. You should create new Path and Paint each time MotionEvent.ACTION_DOWN is fired
Remove the path.reset in switch condition. The draw works. But color does change even for previous draw. You resetting the paths which is clearing the previous draw.
I would use a different pair (path and paint) everytime to draw.
In case you want to draw using canvas the below code work's just fine.
I would also add a color picker to allow user to pick color of his choice.
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;
public MyView(Context c) {
super(c);
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.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);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
// 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;
}
}
You need to use only one Path and Paint object.
A detailed tutorial on this whole thing can in fact be found here:
Making a basic single touch drawing app on Android - Creative Punch

Categories

Resources