Get the touch position inside the imageview in android - android

I have a imageview in my activity and I am able to get the position where the user touch the imageview, through onTouchListener. I placed another image where the user touch over that image. I need to store the touch position(x,y), and use it in another activity, to show the tags. I stored the touch position in the first activity. In the first activity, my imageview at the top of the screen. In the second activity its at the bottom of the screen. If I use the position stored from the first acitvity, it place the tag image at the top, not on the imageview, where I previously clicked in the first activity. Is there anyway to get the position inside the imageview.
FirstActivity:
cp.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
x = (int) event.getX();
y = (int) event.getY();
Log.v("touched x val of cap img >>", x + "");
Log.v("touched y val of cap img >>", y + "");
tag.setVisibility(View.VISIBLE);
int[] viewCoords = new int[2];
cp.getLocationOnScreen(viewCoords);
int imageX = x - viewCoords[0]; // viewCoods[0] is the X coordinate
int imageY = y - viewCoords[1]; // viewCoods[1] is the y coordinate
Log.v("Real x >>>",imageX+"");
Log.v("Real y >>>",imageY+"");
RelativeLayout rl = (RelativeLayout) findViewById(R.id.lay_lin);
ImageView iv = new ImageView(Capture_Image.this);
Bitmap bm = BitmapFactory.decodeResource(getResources(),
R.drawable.tag_icon_32);
iv.setImageBitmap(bm);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.leftMargin = x;
params.topMargin = y;
rl.addView(iv, params);
Intent intent= new Intent(Capture_Image.this,Tag_Image.class);
Bundle b=new Bundle();
b.putInt("xval", imageX);
b.putInt("yval", imageY);
intent.putExtras(b);
startActivity(intent);
return false;
}
});
In TagImage.java I used the following:
im = (ImageView) findViewById(R.id.img_cam22);
b=getIntent().getExtras();
xx=b.getInt("xval");
yy=b.getInt("yval");
im.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int[] viewCoords = new int[2];
im.getLocationOnScreen(viewCoords);
int imageX = xx + viewCoords[0]; // viewCoods[0] is the X coordinate
int imageY = yy+ viewCoords[1]; // viewCoods[1] is the y coordinate
Log.v("Real x >>>",imageX+"");
Log.v("Real y >>>",imageY+"");
RelativeLayout rl = (RelativeLayout) findViewById(R.id.lay_lin);
ImageView iv = new ImageView(Tag_Image.this);
Bitmap bm = BitmapFactory.decodeResource(getResources(),
R.drawable.tag_icon_32);
iv.setImageBitmap(bm);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
30, 40);
params.leftMargin =imageX ;
params.topMargin = imageY;
rl.addView(iv, params);
return true;
}
});

You can get the top left corner of your view as follows:
int[] viewCoords = new int[2];
imageView.getLocationOnScreen(viewCoords);
From this and the touch coordinates you can calculate the point inside the ImageView:
int touchX = (int) event.getX();
int touchY = (int) event.getY();
int imageX = touchX - viewCoords[0]; // viewCoords[0] is the X coordinate
int imageY = touchY - viewCoords[1]; // viewCoords[1] is the y coordinate

Add these lines to ImageView
android:scaleType="fitXY"
and
android:adjustViewBounds="true"
to your image view it is because image are not having their original dimensions in IV

Related

Get x,y of image in Imageview onClick() with scale type fitCenter

I have an ImageView, by using image resolution I have placed canvas objects on top of that Image
when I touched the ImageView it should return x,y of image not Imageview.
I don't want use FitXY scale type
currently I am getting x,y of Imageview
iv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
float x = (event.getX())/2; // or getRawX();
float y = (event.getY())/2;
System.out.println("drawn bounds:cx: "+x+"cy: "+y);
return false;
}
});
Please help me to get x,y of image rather than Imageview.
Try this to get XY of image
float bitmapWidth = bitmap.getWidth();
float bitmapHeight = bitmap.getHeight();
float imageWidth = iv.getWidth();
float imageHeight = iv.getHeight();
float proportionateWidth = bitmapWidth / imageWidth;
float proportionateHeight = bitmapHeight / imageHeight;
int tapX = (int) (event.getX() * proportionateWidth);
int tapY = (int) (event.getY() * proportionateHeight);
Hope its help!

Moving only bitmap inside an ImageView

I have an ImageView with a black background set in xml, and in code I'm placing bitmap with imageView.setImageBitmap(bitmap);
You can select between ScaleType.CENTER_CROP and ScaleType.CENTER_INSIDE.
If ScaleType.CENTER_INSIDE is selected, bitmap is smaller than the ImageView, and the black background is visible.
I would like to move only bitmap across the screen. I tried with this code, but it moves whole ImageView, not only bitmap inside ImageView.
imageView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int eid = event.getAction();
switch (eid) {
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
int x = (int) event.getRawX();
int y = (int) event.getRawY();
layoutParams.leftMargin = x - 50;
layoutParams.topMargin = y - 100;
imageView.setLayoutParams(layoutParams);
break;
default:
break;
}
return true;
}
});
Is there a way to only move bitmap that's inside ImageView?
Also I would like to increase and decrease width and height of a bitmap and maintain the bitmap's aspect ratio.
I tried with this, but it's not working:
buttonIncrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
layoutParams.width = (int) ((layoutParams.width + 10) * scale + 0.5f);
layoutParams.height = (int) ((layoutParams.height + 10) * scale + 0.5f);
}
});

Pinch to zoom IN or OUT imageview added dynamically to Layout

I working on an application where in the ImageView is created dynamically and added to the layout, after the user selects image from the gallery of the device.
With the code what I have written, am able to move and rotate the ImageView. But, I also want to implement Pinch zoom in/out for the ImageView.
The bug which exists in the code is when after the ImageView is added to the layout, the ImageView when taken to the extreme right shrinks so that what I want to do, but that should happen on the pinch.
EDIT: After debugging my code I found that i want to increase the size of the ImageView by increasing the width and height.
When i changed the following line :
final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
To:
final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
240,
200);
I got what i wanted. So can I do this inside the class DragImageView on pinch.
Here's the code for the custom Imageview.
public class DragImageView extends ImageView {
private float mLastTouchX;
private float mLastTouchY;
private float mDeltaX;
private float mDeltaY;
private Bitmap bmpImg;
Context mContext;
public DragImageView(Context context, Bitmap bmpImg) {
super(context);
this.bmpImg = bmpImg;
this.mContext = context;
init();
}
public DragImageView(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// TODO Auto-generated method stub
Bitmap resized = Bitmap.createScaledBitmap(bmpImg, 180, 200, true);
Bitmap conv_bm = getRoundedShape(resized); //function to get the imageview as rounded shape
setImageBitmap(conv_bm);
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(final View v, MotionEvent event) {
PopupMenu popup = new PopupMenu(mContext, v);
// Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu,
popup.getMenu());
popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
int itemId = item.getItemId();
if (itemId == R.id.delete_DragImgView) {
ViewGroup parentView = (ViewGroup) v.getParent();
parentView.removeView(v);
} else if (itemId == R.id.rotate_DraagImgView) {
final RotateAnimation rotateAnim = new RotateAnimation(
0.0f, 90, RotateAnimation.RELATIVE_TO_SELF,
0.5f, RotateAnimation.RELATIVE_TO_SELF,
0.5f);
rotateAnim.setDuration(0);
rotateAnim.setFillAfter(true);
v.startAnimation(rotateAnim);
}
return false;
}
});
final int action = event.getAction();
mLastTouchX = event.getRawX();
mLastTouchY = event.getRawY();
switch (action) {
case MotionEvent.ACTION_DOWN: {
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) getLayoutParams();
mDeltaX = mLastTouchX - lParams.leftMargin;
mDeltaY = mLastTouchY - lParams.topMargin;
popup.show();
break;
}
case MotionEvent.ACTION_MOVE: {
mLastTouchX = event.getRawX();
mLastTouchY = event.getRawY();
final RelativeLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.leftMargin = (int) (mLastTouchX - mDeltaX);
params.topMargin = (int) (mLastTouchY - mDeltaY);
setLayoutParams(params);
break;
}
}
invalidate();
return true;
}
});
}
The imageview is added as follows from the activity.
final DragImageView dynamicImgView = new DragImageView(
getApplicationContext(), yourSelectedImage);
final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
dynamicImgView.setLayoutParams(params);
relativeLayout.addView(dynamicImgView);
I know the pinch to zoom is possible but after trying lots of codes and Help from stackover flow, thought of finally putting it on so.
Please help me. Thanks in advance.
Solved my problem.. I simply increased the height & width of the imageview. Code
} else if (itemId == R.id.zoom_in) {
if (height > 100) {
height = height - ZoomCounter;
width = width - ZoomCounter;
final RelativeLayout.LayoutParams params = (LayoutParams) getLayoutParams();
getLayoutParams().height = height;
getLayoutParams().width = width;
setLayoutParams(params);
invalidate();
}
} else if (itemId == R.id.zoom_out) {
if (height < 600) {
height = height + ZoomCounter;
width = width + ZoomCounter;
final RelativeLayout.LayoutParams params = (LayoutParams) getLayoutParams();
getLayoutParams().height = height;
getLayoutParams().width = width;
setLayoutParams(params);
invalidate();
}
}

FIT_XY not working when scaling and rotating image using Matrix

I'm trying to resize and rotate an image and I want the full image to be shown, not a cropped version of the image. I have a resize button next to the image that when it is pressed performs the resize/rotation. I tried setting the scale type of the ImageView to FIT_XY and then tried FIT_CENTER but the image is always cropped, not scaled properly.
//MainActivity code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout container = (RelativeLayout) findViewById(R.id.container);
RelativeLayout.LayoutParams layoutParamsImage = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LinearLayout l1 = new LinearLayout(getApplicationContext());
LinearLayout l2 = new LinearLayout(getApplicationContext());
l2.setOrientation(LinearLayout.VERTICAL);
ImageView imageView = new ImageView(getApplicationContext());
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.butterfly);
imageView.setImageBitmap(bitmap);
ImageView resizeButton = new ImageView(getApplicationContext());
resizeButton.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent motionEvent) {
LinearLayout stickerContainer = (LinearLayout) v.getParent().getParent();
ImageView stickerImage = (ImageView) stickerContainer.getChildAt(0);
double r=Math.atan2(motionEvent.getX()-stickerImage.getWidth(), stickerImage.getHeight()-motionEvent.getY());
int rotation=(int)Math.toDegrees(r);
int y = (int) motionEvent.getY();
int x1=0;
int y1=0;
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
x1 = (int) motionEvent.getX();
y1= (int) motionEvent.getY();
}
else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
int x2 = (int) motionEvent.getX();
int y2= (int) motionEvent.getY();
int height = Math.abs(y2-y1) *2;
int width = Math.abs(x2-x1) *2;
width = Math.max(width, 100);
height = Math.max(height, 100);
width = Math.min(width, 500);
height = Math.min(height, 500);
width=height;
float newRot=new Float(rotation);
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.butterfly);
Matrix matrix=new Matrix();
matrix.postRotate(newRot,width,height);
matrix.postScale(2, 2);
stickerImage.requestLayout();
stickerImage.getLayoutParams().height = height;
stickerImage.getLayoutParams().width = width;
//Bitmap reDrawnBitmap=Bitmap.createBitmap(bitmap,0,0,width, height,matrix,true);
Bitmap reDrawnBitmap=Bitmap.createBitmap(bitmap,0,0,stickerImage.getWidth(), stickerImage.getHeight(),matrix,true);
//Bitmap reDrawnBitmap=Bitmap.createScaledBitmap(bitmap, dstWidth, dstHeight, filter)
stickerImage.setScaleType(ImageView.ScaleType.FIT_XY);
stickerImage.setAdjustViewBounds(true);
stickerImage.setImageBitmap(reDrawnBitmap);
stickerImage.setScaleType(ImageView.ScaleType.FIT_XY);
}
return true;
}
});
resizeButton.setBackgroundResource(R.drawable.resize);
layoutParamsImage.height = 100;
layoutParamsImage.width = 100;
imageView.setLayoutParams(layoutParamsImage);
l1.addView(imageView);
l2.addView(resizeButton);
l1.addView(l2);
//imageView.setMaxHeight(100);
//imageView.setMaxWidth(100);
container.addView(l1);
}
}
//layout code activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.doodle4.MainActivity"
tools:ignore="MergeRootFrame"></RelativeLayout>
I figured out the scaling part. I need to create a scaled Bitmap after creating the bitmap that is created using matrix.
In the
else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
code block use this code instead of what's there at the bottom:
Bitmap reDrawnBitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(), bitmap.getHeight(),matrix,true);
Bitmap reDrawnBitmapRescaled=Bitmap.createScaledBitmap(reDrawnBitmap, width, height, false);
stickerImage.setImageBitmap(reDrawnBitmapRescaled);

How to Bring layout back to its original position in android after drag

I have working on a project. where I need to drag the layout, I manage to move (drag) the layout but when I release the touch it is not coming at its original position.
Please anyone tell me what should I do in MotionEvent.ACTION_UP so that I can get layout back to its original position.
Following is my code.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class HomeActivity extends Activity implements OnTouchListener {
RelativeLayout _view;
RelativeLayout _view1;
// TextView _view;
ViewGroup _root;
private int _xDelta;
RelativeLayout.LayoutParams lParams;
RelativeLayout.LayoutParams mainlParams;
private int _yDelta;
// private int X1, Y1, width;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_root = (ViewGroup) findViewById(R.id.root);
_view = (RelativeLayout) findViewById(R.id.relativeLayout);
_view.setOnTouchListener(this);
lParams = (RelativeLayout.LayoutParams) _view.getLayoutParams();
mainlParams = (RelativeLayout.LayoutParams) _view.getLayoutParams();
// _root.addView(_view1);
}
public boolean onTouch(View view, MotionEvent event) {
int X = (int) event.getRawX();
int Y = (int) event.getRawY();
RelativeLayout.LayoutParams layoutParams;
lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
Log.e("", "inside ACTION_DOWN");
lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
Log.e("", "inside ACTION_UP");
if ((X - _xDelta) < -150) {
_root.removeView(_view);
} else {
view.setLayoutParams(mainlParams);
}
break;
case MotionEvent.ACTION_MOVE:
Log.e("", "inside ACTION_MOVE");
layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
break;
}
_root.invalidate();
return true;
}
}
NEW EDIT
here I show you a very simple (and by the way not very clean code) how to do what you want to do. I have a relativeLayout with a green LinearLayout inside:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/moving_layout"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#00ff00"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</LinearLayout>
</RelativeLayout>
Then in Your MainActivity, set the topLayout, where the view You want to move is inside, to onTouchListener. Set originalX and originalY at ACTION_DOWN and moveX and moveY at ACTION_MOVE. When user release fingers, go back to original position:
public class MainActivity extends Activity implements OnTouchListener {
private LinearLayout mLinearLayout;
private RelativeLayout mRelativeLayout;
private RelativeLayout.LayoutParams params;
private float originalX = 0;
private float originalY = 0;
private float moveX = 0;
private float moveY = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLinearLayout = (LinearLayout) findViewById(R.id.moving_layout);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relative_layout);
mRelativeLayout.setOnTouchListener(this);
int width = getMetrics(100);
int height = getMetrics(100);
params = new RelativeLayout.LayoutParams(width, height);
}
/**
* converts dp to px
*
* #param dp
* #return
*/
private int getMetrics(int dp) {
DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
return (int) ((dp * displayMetrics.density) + 0.5);
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case (MotionEvent.ACTION_DOWN):
originalX = event.getX(); //set X start position
originalY = event.getY();//set Y start position
moveX = event.getX();//first move x
moveY = event.getY();//first move y
break;
case (MotionEvent.ACTION_MOVE):
moveX = event.getX();//set move x
moveY = event.getY();//set move y
//set LayoutParams to mLinearLayout
params.leftMargin = (int) moveX;
params.topMargin = (int) moveY;
mLinearLayout.setLayoutParams(params);
break;
case (MotionEvent.ACTION_UP):
//set mLinearLayout back to original position
params.leftMargin = (int) originalX;
params.topMargin = (int) originalY;
mLinearLayout.setLayoutParams(params);
break;
}
return true;
}
}
DonĀ“t wonder about the getMetrics() Method, this is because setting same width and height to mLinearLayout like defined in xml. In xml, you set this values as dp, at LayoutParams, it is px. But this is not relevant for Your question.
What I am doin here is, set original X and Y at ACTION_DOWN and get back to this at ACTION_UP. So, everytime the user press down again, these values will be "renewed", the layout will going back to the last points of ACTION_DOWN if fingers will release. This should give You an idea how to handle your problem.

Categories

Resources