Pin several images at touch points - Android - android

Am trying to place pins wherever the user touches on an imageView. Assume a map (like Google Maps) & the user touches a point, say point A, and a pin is drawn at that point. Then, the user touches point B, then another pin (not the same previous pin relocated!) needs to be drawn at point B and so on. Right now, am able to draw a pin at the point where the user touches on the screen like this :
#Override
public void onDraw(Canvas canvas) {
....
Bitmap marker = BitmapFactory.decodeResource(getResources(),
R.drawable.icon_locationmarker);
canvas.drawBitmap(marker, mLastTouchX, mLastTouchY, null);
....
canvas.restore();
}
However, I don't want to relocate one pin across the screen wherever the user touches (which is what the above code is doing). I want to put several pins at all points wherever user touches. Am new to Android. Please help.

Eluvatar is right, you needs to create a list to store all your mark. Here's the sample of code. Remember, do add list when only motionEvent is either Action_UP or Action_DOWN only. Otherwise, there will be full of point.
public ArrayList<Coordinate> pointsList;
#Override
public void onDraw(Canvas canvas) {
....
Bitmap marker = BitmapFactory.decodeResource(getResources(),
R.drawable.icon_locationmarker);
for(Coordinate coor : pointsList){
canvas.drawBitmap(marker, coor.x, coor.y, null);
}
....
canvas.restore();
}
public View.OnTouchListener mListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
pointsList.add(new Coordinate(event.getX(), event.getY()));
}
return false;
}
};
class Coordinate{
float x;
float y;
public Coordinate(float x, float y){
this.x = x;
this.y = y;
}
}
edit: change int x,y to float x,y

you need to create a list of "touch points". then on touch add a new touch point to the list, then onDraw you iterate through that list and draw a marker on each point.
you'll also need to make sure you save the list of touch points on save instance state otherwise you'll lose them on rotate and on activity pause.

Related

How much priority does scrollBy have over canvas onDraw?

This is a basic code for detecting touch + drawing a custom view :
public boolean onTouchEvent(MotionEvent event) { //Basic onTouch code for scrolling along the Y axis
super.onTouchEvent(event);
if(event.getActionMasked()==MotionEvent.ACTION_DOWN){
mPrevious = event.getY();
}
if(event.getActionMasked()==MotionEvent.ACTION_MOVE){
float distance = mPrevious - event.getY();
scrollBy(0,Math.round(distance));
mPrevious = event.getY();
}
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Basic drawing of a circle at (200,200)
canvas.drawCircle(200f,200f,50f, defaultPaint);
//canvas.setMatrix(new Matrix());
Log.d("CANVAS", "("+canvas.getMatrix().toString()+")");
}
I'm working with a custom view, I'm trying to implement user scrolling functionality using scrollBy, but it looks like I'll have to create the logic myself.
I still want to understand how this function works. When I print log the canvas matrix in the last line, it correctly displays the new coordinates, and onDraw is called every time the touch moves.
But if I uncomment canvas.setMatrix, suprisingly nothing changes functionality-wise. The only difference now is that the console log shows that the canvas matrix is always equal to identity mx, even if it's correctly being scrolled. Why? How can scrollBy completely overwrite canvas drawing?

Drawing a line following finger - motionevent.getX() and getY() incorrect UPDATE

UPDATE: please read entire question again :-)
Background:
I have created a grid of dots by creating a custom view and then adding these views to a TableLayout. The aim is for me to be able to draw a line from one of these dots to another dot in a way so that when a dot is pressed, a line is started from the center of the pressed dot to the point where the finger is currently touching. When the finger is dragged over another dot, the line then finishes at the center of that dot. The result being a line drawn from the center of the pressed dot to the center of the dot which was dragged over by the finger.
To create a line going over the TableLayout, I created a new custom view which just created a line between points with the canvas.drawLine() method. I then created a FrameLayout in which I put the TableLayout and the LineView. This meant the line view would be able to be drawn on top of the TableLayout.
Current Situation:
I have added touch listener in the DotView class so that it can have its own “touch feedback”. There is also another touch listener in the activity which I am trying to use to get the points needed to draw the line. The touch listeners are working fine as far as I can tell - they are not interfering with each other.
The problem is getting the correct coordinates to plot the line. I have tried a number of ways to get the coordinates of the center of the dot that was pressed (the starting point of the line), but I still have not managed it. This question, has more information: Get the coordinates of the center of a view . The second part is getting the correct end point of the line. For the purposes of this question, I would just like the end of the line to follow the position of the finger. I thought it was as easy as motionevent.getX() / getY() but this hasn’t worked. What happened instead was that there was a mix up between the coordinates on a scale relative to the layout of the dot and the coordinates relative to the whole layout/screen.
Simply put: the getX() and getY() values are incorrect, and this is what I am trying to solve here.
As shown in the screenshots, when I press down on a dot, the start point of the line is roughly in the right place, but the end point is way off. I can’t really explain why.
I have tried getRawX() and getRawY() and they return more much more accurate values, but they are still incorrect by the amount of padding (or something like that - I don’t 100% understand).
This shows my code
In my Activity :
LineView test;
FrameLayout fl;
float startPointX = 0;
float startPointY = 0;
// Removed
#Override
public boolean onTouch(View view, MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
int[] loc = new int[2];
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (view instanceof DotView) {
DotView touchedDv = (DotView) view;
int dotColor = touchedDv.getColor();
test.setColor(dotColor);
float[] f = touchedDv.getDotCenterLocationOnScreen();
startPointX = f[0];
startPointY = f[1];
test.setPoints(startPointX, startPointY, eventX, eventY);
fl.addView(test);
}
vib.vibrate(35);
return false;
case MotionEvent.ACTION_MOVE:
test.setPoints(startPointX, startPointY, eventX, eventY);
break;
case MotionEvent.ACTION_UP:
fl.removeView(test);
return false;
default:
return false;
}
return true;
}
And finally the LineView:
public class LineView extends View {
public static final int LINE_WIDTH = 10;
Paint paint = new Paint();
float startingX, startingY, endingX, endingY;
public LineView(Context context) {
super(context);
paint.setColor(Color.MAGENTA);
paint.setStrokeWidth(LINE_WIDTH);
}
public void setPoints(float startX, float startY, float endX, float endY) {
startingX = startX;
startingY = startY;
endingX = endX;
endingY = endY;
invalidate();
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawLine(startingX, startingY, endingX, endingY, paint);
}
NOTES:
I am calling the top left hand dot "dot 1".
The screenshots may not be entirely accurate as my finger moves
slightly when I take the screenshot, but the behaviour I described is
happening.
If any other information/code is wanted, I will happily provide it.
Thanks for taking the time to read this - sorry it is so long!
I have added touch listener in the DotView class so that it can have
its own “touch feedback”. There is also another touch listener in the
activity which I am trying to use to get the points needed to draw the
line. The touch listeners are working fine as far as I can tell - they
are not interfering with each other.
I don't quite see why you need both touch listener. To draw the line the touch listener on the TableLayout should be more than enough.
The problem with your code(or at least from what I've seen) is that you use the getLocationOnScreen(coordsArray) method without translating the returned values back to the coordinates system of the LineView. For example, you get the coordinates of a DotView which will be x and y. You then use this values in the LineView. But, the LineView when it will do its drawings will use its own(standard) coordinates system which places the top-left of the view at (0,0) and the coordinates will not match. Here's an example: suppose you touch the very first DotView which has a height of 50 and the y returned by the getLocationOnScreen() method is 100. You calculate the center of the DotView wich will come be at 125(100 + 50 / 2). Using this value in the LineView will be way off the normal position as the actual drawing will be done at 125, which in screen coordinates will visually translate to a y of 225 (100 returned by getLocationOnScreen() + 125).
Anyway I've made a small example using the getLocationOnScreen() method to do what you're trying to do(which you can find here).

Technique to make a canvas drawLine() clickable?

I'm working on an app that plots nodes on a map, and each node has edges that are represented by a line between them. I've drawn the edges using Canvas and drawLine(), but it would be useful if the lines themselves could be clickable. By that I mean a method of allowing the user to touch the line or think they're touching the line and an event can trigger. (like display edge info, etc...)
I can't rightly attach a touch event to a line I've drawn with Canvas, so I was thinking of placing ImageViews inbetween the ends of each edge line that's drawn. The ImageView could be a dot so it's clear where the touch event triggers.
Does anyone have any other suggestions? I'm mainly looking for ideas that I've missed. Maybe there's something in the Android API that can help with this that I'm unaware of.
Thanks in advance for any tips!
Use a path to draw the line:
Path linePath;
Paint p;
RectF rectF;
float point1X, point1Y, point2X, point2Y;
// initialize components
// draw the line
linePath.moveTo(point1X, point1Y);
linePath.lineTo(point2X, point2Y);
canvas.drawPath(linePath, p);
linePath.computeBounds(rectF, true);
Override onTouchEvent(MotionEvent):
#Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (rectF.contains(touchX, touchY)) {
// line has been clicked
}
break;
}
return true;
}

Put a custom pin over an image and get its coordinates

I have an ImageView with an image loaded,
I want that when the user clicks in a point of the image, another little image(used as pin) is overlapped in this point and the coordinates of the point are returned.
But I haven't idea of how could I do this.
To place a image at a certain coordinates you will have to draw the image on the canvas .
To get the coordinates of the touch event use the following code:
#Override
public void onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
mTouchX = event.getX();
mTouchY = event.getY();//stores touch event
} else {
mTouchX = -1;
mTouchY = -1;
}
super.onTouchEvent(event);
}
Here is the code for drawing the image on canvas Image in Canvas with touch events
hope it helps.
Try this,
It will help you to place image based on the co-ordinates. So it can be overlapped
Link 1

Android: How to draw simple graphics on a large scrolling canvas

In Android, I need to be able to draw simple graphics (points, lines, circles, text) on a large scrollable canvas (i.e the phone's screen is a viewport in a much larger area). I have hunted for tutorials on how to do this without success.
"World Map FREE" on Android market is a good example of the sort of effect I need to achieve.
This must be a common problem, so I'm surprised I can't find examples.
I've had to implement something fairly recently of this sort. Basically I had coordinates in my custom view that would shift where objects would be drawn, via some auxiliarry functions:
public class BoardView extends View {
//coordinates to shift the view by
public float shiftX=0f;
public float shiftY=0f;
//used in the dragging code
public float lastX=-1f;
public float lastY=-1f;
/*...*/
//functions that take into account the shifted x and y values
//pretty straightforward
final public void drawLine(Canvas c,float x1,float y1,float x2,float y2,Paint p){
c.drawLine(x1+shiftX, y1+shiftY, x2+shiftX, y2+shiftY, p);
}
final public void drawText(Canvas c,String s,int x,int y,Paint p){
c.drawText(s, x+shiftX, y+shiftY, p);
}
/*etc*/
To actually implement the dragging, I wrote a custom onTouchEvent method to implement dragging:
public boolean onTouchEvent(MotionEvent event){
int eventaction=event.getAction();
float x=event.getX();
float y=event.getY();
switch(eventaction){
case MotionEvent.ACTION_DOWN:
time=System.currentTimeMillis();//used in the ACTION_UP case
break;
case MotionEvent.ACTION_MOVE:
if(lastX==-1){ lastX=x;lastY=y;}//initializing X, Y movement
else{//moving by the delta
if(Math.abs(x-lastX)>1 || Math.abs(y-lastY)>1){//this prevents jittery movement I experienced
shiftX+=(x-lastX);//moves the shifting variables
shiftY+=(y-lastY);//in the direction of the finger movement
lastX=x;//used to calculate the movement delta
lastY=y;
invalidate();//DON'T FORGET TO CALL THIS! this redraws the view
}
}
break;
case MotionEvent.ACTION_UP: //this segment is to see whether a press is a selection click(quick press)
//or a drag(long press)
lastX=-1;
if(System.currentTimeMillis()-time)<100)
try {
onClickEvent(x,y);//custom function to deal with selections
} catch (Exception e) {
e.printStackTrace();
}
break;
}
return true;
}
Look into tile engines, there's a lot to find on Google about them.

Categories

Resources