Get X/Y coordinates on ImageView touch - java

So, I need to get coordinates of my touch on ImageView.
I have already successfully tried to get coordinates in OnTouchListener event. But it is not what i really need.
The problem is that the resolution of the screen is much lower than the resolution of the picture in ImageView.
How to get actual coordinates (maybe certain pixels) of the image?

Android: How do I get the x y coordinates within an image / ImageView?
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
int[] values = new int[2];
view.getLocationOnScreen(values);
Log.d("X & Y",values[0]+" "+values[1]);
}
});
Something like this?

There's getLocationOnScreen() and getLocationInWindow() methods for the purpose.
imageView.setOnTouchListener(new OnTouchListener() {
#Override public boolean onTouch(View view, MotionEvent motionEvent) {
int[] locations = new int[2];
view.getLocationOnScreen(locations);
//view.getLocationInWindow(locations);
return false;
}
});

Related

How can I interact with animations?

I have an animation that slides across the screen, while the animation is playing I want it to disapear if it has been clicked!
I have tried to use OnClickListener() and also OnClickMethods, both only work after the animation has finished playing!
TranslateAnimation animation = new TranslateAnimation(answer, answer, 0, height * -1); // xfrom , xto, y from,y to
animation.setDuration(5000);
Floater0.startAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
if (AdPlayer0.isPlaying()) {
answer = rn.nextInt(width) + 1; //useless
TranslateAnimation animation0 = new TranslateAnimation(answer, answer, 0, height * -1); // xfrom , xto, y from,y to
animation0.setDuration(5000);
animation0.setFillEnabled(true);
Floater1.startAnimation(animation0);
Floater1.setVisibility(View.VISIBLE);
Floater0.startAnimation(animation);
}
}
});
I was reading the answer here and something interesting was mentioned:
Animations do NOT effect the 'physical' location of the views on screen. If you want it to actually move then you need to adjust the properties of the view.
I have now tested the above quote, and it seems to be true! I have also looked into how to adjust the position properties of the view after the animation has ended, however I want to change its position before an animation has ended(While its playing)!
Any suggestions for a work around? ideally I would want to change the physical position of the view while the animation is played!
A TranslationAnimation only moves the pixels on the screen, so an OnClickListener does not animate with it. Use ViewPropertyAnimator instead and set an OnClickListener then it should work.
The code would look something like this :
Floater1.animate().setDuration(5000).translationX(answer).translationY(height * -1);
Check out all the available methods in the docs.
Edit/Update :
.translationX(float toX)
means -> animate the view to this point on the x axis.
The animation always starts at the current position of the view, so you don't need a fromX. There are also other methods which you can use :
.translationXBy(float byX)
.translationYBy(float byY)
With these you can translate the view BY the float value, and not TO a certain point on the screen.

How To Change The Bitmap Resource On TouchEvent

This Should be easy and simple right?!
So, i have a Gameobject as a Button i reference it on a GamePanel that extents SurfaceView like this :
bby = new Buttons(BitmapFactory.decodeResource(getResources(), R.drawable.babybutton),123 ,114 ,1);
bby is drawn and work fine,
my problem is How can i change the Resource (R.drawble.babybutton) to a different resource for e.g (R.drawble.babybutton2) on Touch?
just like pressing buttons animations!
Thanks in advance
(If my question look stupid please don't dislike! i'm very new to this).
if you want to change the button's drawable on touch on the surfaceview. than you can override this method in your surfaceview class.
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
//here you can set an another drawable to your button or can do something else
break;
}
return true;
}
In your activity set a touchListener on the surfaceview.
after initialize the surfaceView. pass this surfaceview to the
surfaceView.setOnTouchListener(surfaceView)
I may have misunderstood you, but if you want to change the button's rescource, this is how you should do it:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runOnUiThread(new Runnable() {
#Override
public void run() {
button.setBackgroundResource(R.drawable.icon);
}
});
}
});

How to get the exact touch position of a image?

I have an idea for implementing of a login with password as the image touch positions when the member touch the same position I have to login the user.Can anyone help me how to implement it I can get the position of screen only. and the x and y coordinated are changing even when I touch the same position.
I would say create a custom View that extends ImageView:
public class PasswordView extends ImageView {
public PasswordView(Context context) {
super(context);
// Any additional PasswordView setup
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float xTouchPos = event.getX();
float yTouchPos = event.getY();
// If the PasswordView was clicked
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Check if they touched in the secret spot
}
return super.onTouchEvent(event);
}
}
By subclassing ImageView, you will still have access to all the standard features of an ImageView (setting an image source, etc.) and you will also be able to add the additional functionality for checking a user's touch position.
Here's an example project that uses onTouchEvent.

Add image to location where user click on Layout

I am trying to add image to the point (X,Y) on Layout i have created dynamicaly.
I want to add the imageview on exact user clicked location. But the image is not placed on correct location when clicked.
here is my code
final LinearLayout layoutColumnBoxes = new LinearLayout(getParent());
layoutColumnBoxes.setBackgroundColor(Color.GREEN);
layoutColumnBoxes.setId(counterIdForBoxes);
layoutColumnBoxes.setLayoutParams(layoutParamsColumns);
layoutColumnBoxes.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(getParent(),"Event="+event.getX()+"Event Y = "+event.getY(),Toast.LENGTH_SHORT).show();
return false;
}
});
layoutColumnBoxes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageView imageView = new ImageView(getParent());
imageView.setImageResource(R.drawable.crack);
LinearLayout lay = (LinearLayout) view.findViewById(v.getId());
lay.addView(imageView);
// Toast.makeText(getParent(),"Clicked View Id is="+v.getId(),Toast.LENGTH_SHORT).show();
}
});
Please help.
See I know what you're trying to say cause I too had this problem a few months back when developing an application. When you click a point on the screen the position of the imageview is not close to the way you clicked it right?
the things I did were
1) remove the excess space around your image.
This is optional. The only reason I stated this was because it depends on the type of image in your image view cause later you will be placing the image based on the top left corner of the imageview.
2) if your loading the images from the drawable folder make sure that you have the right size image in the right folder. This is IMPORTANT. if you screw up the sizes, android is going to alter the size and location of your images based on when your touch is based on the screen.
3) you need to set the margins of your image view properly. After hours of googling I came up with the following first you'll need to get half the height and width of your imageview, use imageview.getMeasuredHeight() / 2 and imageview.getMeasuredWidth() / 2 (Call these imgH and imgW respectively for explanation purposes)
the later in your OnTouchListener you'll have to set the top left margin of your imageview (the methods vary on the type of layout you use). This is done by setting the top margin at "event.getY - imgH" and the left margin at "event.getX - imgW"
I have an app in the playstore which uses this feature, you can check it here .
I hope this has solved your problem :) if it hasn't then don't hesitate to speak your doubts.
this code work for me:
public class MainActivity extends ActionBarActivity {
float x, y;
RelativeLayout rl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().hide();
rl = (RelativeLayout) findViewById(R.id.root_view);
rl.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
// rl.removeView(iv);
x = motionEvent.getX();
y = motionEvent.getY();
setImageLocation(x, y);
//rl.addView(iv);
}
return false;
}
});
}
public void setImageLocation(float x, float y) {
ImageView newImage;
RelativeLayout.LayoutParams newparams;
newparams = new RelativeLayout.LayoutParams(20, 20);
newparams.setMargins((int) (x-rl.getPaddingLeft()), (int) (y-rl.getPaddingTop()), 0, 0);
newImage = new ImageView(this);
newImage.setLayoutParams(newparams);
newImage.setImageResource(R.drawable.clock);
rl.addView(newImage);
}
}
activity_main.xml layout only has one relativeLayout that has full screen size(match parent)

Add an image as background and put other images on top of it

I am creating an image by using Canvas- and Bitmap class. I want to set it as a background for the user. Then I want to add some more images on top of it.
this is the code for image that is supposed to be as background.
ImageView imgMap1 = (ImageView) findViewById(R.id.imgMap1);
imgMap1.setImageDrawable(new BitmapDrawable(Bitmap.createBitmap(bmp, 0, 0, 500, 500)));
and this is the code to make it as background:
LinearLayout ll = new LinearLayout(this);
ll.setBackgroundResource(R.drawable.nn);
this.setContentView(ll);
The Problem here is: When I set it as background, I can't see the other photo anymore.
How can I do this?
Thanks in advance.
The other Images are added in the Layout. they are movable by finger touch. user can reposition them by finger.
ImageView i1 = (ImageView) findViewById(R.id.Image1);
ImageView i2 = (ImageView) findViewById(R.id.Image2);
The layout is built from the top down in your XML file, or in the order you add elements in code. It sounds like your other images is being added to the layout first, either as a higher-up element in the XML file, or earlier in your code. You'll need to add the other code as context for a complete answer.
Just noticed that you can directly set Bitmap as your ImageView's content using setImageBitmap(Bitmap bm)See the Android Reference
Then let talk about your question.
First, create your own class extends the View;
Second, load background image and overlay image using Bitmap
Third, invoke onTouch event, so that the onDraw method will automatically redraw the overlay image using the coordinates returned by onTouch
Something like:
public class dragndrop extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// using this to load your background image
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565; // this is not a must
bmBackground = BitmapFactory.decodeFile(filePath, opt);
super.onCreate(savedInstanceState);
DrawView dv = new DrawView(dragndrop.this);
setContentView(dv);
}
public class DrawView extends View {
Point coordinate;
public DrawView(Context context) {
super(context);
setFocusable(true); //necessary for getting the touch events
}
#Override
protected void onDraw(Canvas canvas) {
// assume you have already load your background image as bitmap
canvas.drawBitmap(bmBackground, 0, 0, null);
// assume bm is the overlay image you need to put on top,
// the method here will draw the object with the coordinate you give
canvas.drawBitmap(bm, coordinate.x, coordinate.y, null);
}
// events when touching the screen
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
int x = (int)event.getX();
int y = (int)event.getY();
switch (eventaction ) {
case MotionEvent.ACTION_DOWN:
// add code here to determine the point user touched is within the object or not
break;
}
}
break;
case MotionEvent.ACTION_MOVE: // touch 'n' drag
// pass the touch point to your object
coordinate.x = x;
coordinate.y = y;
break;
case MotionEvent.ACTION_UP:
// touch drop - just do things here after dropping
break;
}
// redraw the canvas
invalidate();
return true;
}
}
}
This is my own snippet, please edit before use, and please let me know when your question is resolved.

Categories