I have a image view (example: a world map) on top of which I have few location points. Location points are image buttons with just a square image and a text written below the square. I have a custom relative layout that handles touch to rotate the globe in a circular fashion.
Now, how to keep the text of the image button to remain parallel to x-axis or in other words, parallel to the width of the screen when I touch and rotate the globe? The image button rotates at an angle on touch and rotate of the globe.
Could anyone provide with the animation required to keep the image button text always parallel to the x-axis on touch and rotation of the background globe? A pointer I had was to move the image button in a small circular fashion (in a invisible circular path) so that the text remains always parallel to the width of the screen. A small drawback with this approach is that the button will move slightly in a circular fashion from its original point of location.
Can anyone help with the Android animation to move the image button on a small circular path on top of a image view?
My layout is as below
`
<com.mycompany.view.RotateRelativeLayout
android:id="#+id/test_relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/test_bottom_bar"
android:layout_marginTop="#dimen/test_margin_top"
android:layout_centerInParent="true">
<ImageView
android:id="#+id/test_globe"
android:layout_width="#dimen/test_layout_width"
android:layout_height="#dimen/test_layout_height" />
<FrameLayout
android:id="#+id/test_frame_layout"
android:layout_width="#dimen/test_layout_width"
android:layout_height="#dimen/test_layout_height">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/test_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"/>
<ImageButton
android:id="#+id/test_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/test_button1"
android:background="#null"/>
</RelativeLayout>
</FrameLayout>
</com.mycompany.view.RotateRelativeLayout>
`
And the custom relative layout which I am using to touch and rotate the globe is as follows
`
public class RotateRelativeLayout extends RelativeLayout {
private float mCenterX, mCenterY;
private float direction = 0;
private float sX, sY;
private float startDirection = 0;
public RotateRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
private double angleBetween2Lines(float centerX, float centerY, float x1,
float y1, float x2, float y2) {
double angle1 = Math.atan2(y1 - centerY, x1 - centerX);
double angle2 = Math.atan2(y2 - centerY, x2 - centerX);
return angle1 - angle2;
}
private void touchStart(float x, float y) {
mCenterX = this.getWidth() / 2;
mCenterY = this.getHeight() / 2;
sX = x;
sY = y;
}
private void touchMove(float x, float y) {
// this calculates the angle the image rotate
float angle = (float) angleBetween2Lines(mCenterX, mCenterY, sX, sY, x, y);
direction = (float) Math.toDegrees(angle) * -1 + startDirection;
}
#Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
setRotation(direction);
super.dispatchDraw(canvas);
canvas.restore();
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// record the start position of finger
touchStart(x, y);
break;
case MotionEvent.ACTION_MOVE:
// update image angle
touchMove(x, y);
break;
case MotionEvent.ACTION_UP:
startDirection = direction;
break;
}
return true;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
onTouchEvent(event);
return super.onInterceptTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
onTouchEvent(event);
return super.dispatchTouchEvent(event);
}
}
`
So, essentially my relative layout should respond to touch events and animate the image button. I have attempted here but this doesn't work
`
final RotateRelativeLayout rotateRelativeLayout = (RotateRelativeLayout) view.findViewById(R.id.test_relative_layout);
rotateRelativeLayout.setOnTouchListener(new View.OnTouchListener() {
private float mCenterX = rotateRelativeLayout.getWidth() / 2.0f;
private float mCenterY = rotateRelativeLayout.getHeight() / 2.0f;
private void animate(View view, double fromDegrees, double toDegrees, long duration) {
final RotateAnimation rotate = new RotateAnimation((float) fromDegrees, (float) toDegrees,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(duration);
rotate.setFillEnabled(true);
rotate.setFillAfter(true);
rotate.setInterpolator(new LinearInterpolator());
rotate.setRepeatCount(1);
view.startAnimation(rotate);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float x = motionEvent.getX();
float y = motionEvent.getY();
final ImageButton imageButton = (ImageButton) view.findViewById(R.id.test_button1);
double angle1 = 0, angle2 = 0;
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
angle1 = Math.toDegrees(Math.atan2(y - mCenterY, x - mCenterX));
break;
case MotionEvent.ACTION_MOVE:
angle2 = Math.toDegrees(Math.atan2(y - mCenterY, x - mCenterX));
animate(imageButton, -angle1, -(angle2-angle1), 0);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
`
Related
this is my current code
Path path_eclipse = new Path();
float radius = (float) (Math.sqrt(Math.pow(r.stopX - r.startX, 2.0f) + Math.pow(r.stopY - r.startY, 2.0f)) / 2.0f);
path_eclipse.addCircle(r.startX, r.startY, radius, Path.Direction.CCW);
canvas.drawPath(path_eclipse, paint);
with this code I am getting as output:
But I want to draw circle like this:
UPDATED Source code: This source code worked in my case
[SOLVED]
[OnDraw]
#Override
protected void onDraw(Canvas canvas) {
Path path_eclipse = new Path();
float centerX = (r.startX + r.stopX) /2;
float centerY = (r.startY + r.stopY) /2;
float radius = (float)Math.sqrt((r.stopX - r.startX)*(r.stopX - r.startX)+(r.stopY - r.startY)*(r.stopY - r.startY));
path_eclipse.addCircle(centerX, centerY, radius/2, Path.Direction.CCW);
canvas.drawPath(path_eclipse,paint);
}
[OnTouchEvent]
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = eventX;
startY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
stopX = eventX;
stopY = eventY;
break;
case MotionEvent.ACTION_UP:
stopX = eventX;
stopY = eventY;
break;
default:
return false;
}
invalidate();
return true;
}
The first two paramateres of addCircle are the x and y coordinates of the center. Assuming A and B are the furthest distance from each other on the circle you want, then the center should a point equidistant to both, hence:
float centerX = (pointA.x + pointB.x) /2
float centerY = (pointA.y + pointB.y) /2
And your radius should be, the distance between A and B, thus:
float radius = (Math.sqrt(Math.pow(x2−x1, 2) + Math.pow(y2−y1, 2))) / 2
Mid points
int mx=(r.stopX + r.startX)/2;
int my= (r.stopy+r.startY)/2;
Radius
float radius = Math.sqrt(Math.pow(r.stopX - my, 2)
+ Math.pow(r.stopY - my, 2));
Edited
I have used code below
public class CustomView extends View {
private Paint paint;
private Circle circle;
private List<Point> points;
public final int CIRCLE_BETWEEN_TWO_POINTS = 1;
private int viewType;
{
paint = new Paint();
points = new ArrayList<>();
}
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onDraw(Canvas canvas) {
switch (viewType) {
case CIRCLE_BETWEEN_TWO_POINTS:
drawView(canvas);
break;
}
}
private void drawView(Canvas canvas){
for(Point point:points){
drawCircle(canvas,new Circle(point.x,point.y,10),false);
}
drawCircle(canvas,circle,true);
}
private void drawCircle(Canvas canvas,Circle circle, boolean isStroke){
paint.reset();
paint.setAntiAlias(true);
if(isStroke){
paint.setStrokeWidth(5);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
}else {
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
}
canvas.drawCircle(circle.getX(), circle.getY(), circle.getRadius(), paint);
}
public void drawCircleBetweenTwoPoints(int x1, int y1, int x2, int y2) {
viewType = CIRCLE_BETWEEN_TWO_POINTS;
points.clear();
points.add(new Point(x1, y1));
points.add(new Point(x2, y2));
int mx = (x1 + x2) / 2;
int my = (y1 + y2) / 2;
double radius = Math.sqrt(Math.pow(x1 - mx, 2)
+ Math.pow(y1 - my, 2));
circle=new Circle(mx,my,(int)radius);
invalidate();
}
}
And called method as
customView.drawCircleBetweenTwoPoints(500,200,100,600);
and its working for me
Click to see output
If you want to draw circle like this, you must know 3 points, then calculate center with radius. Because two points cannot uniquely determine a circle. You can find only whole line of possible centers.
On the other hand, if we consider that two points are exactly opposite. Then you should calculate center by midpoint formula:
M = [(x1 + x2 / 2), (y1 + y2 / 2)]
Next, you can do the same thing as at first case. First, calculate radius and then draw circle.
Assuming, that A and B are exactly opposite to each other, the line segment defined by them will pass through the centre of the circle (C), and the latter will cut AB in half.
Thus:
You calculate then distance of the two points, and divide by two. So you'll have the radius.
The centre of the circle will be exactly halfway between the two: x=(x1+x2)/2 and y=(y1+y2)/2.
If they happen to be just random points, you can use one of these techniques:
Link
Link
In this case however, your problem is slightly tricky, as two points and a radius will not determine one circle unambiguously: the problem will have two solutions.
Guys I know How to draw circle in android..But what I need is using onTouch method to rotate that circle depending on the user hand movement on that circle. Please help.
public class MainActivity extends Activity {
public class SampleView extends View {
Paint mPaint = new Paint();
private Animation anim;
public SampleView(Context context) {
super(context);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(10);
mPaint.setColor(Color.RED);
}
private void createAnimation(Canvas canvas) {
anim = new RotateAnimation(0, 360, getWidth()/2, getHeight()/2);
anim.setRepeatMode(Animation.RESTART);
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(10000L);
startAnimation(anim);
}
protected void onDraw(Canvas canvas) {
int cx = getWidth()/2; // x-coordinate of center of the screen
int cy = getHeight()/2; // y-coordinate of the center of the screen
// Starts the animation to rotate the circle.
if (anim == null)
createAnimation(canvas);
canvas.drawCircle(cx, cy, 150, mPaint); // drawing the circle.
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
}
First, we have to determine the angle between old and new position of circle (as below figure).
cos a = uv / (|u|*|v|)
The simple equation may be
double tx = touch_x - center_x, ty = touch_y - center_y;
double t_length = Math.sqrt(tx*tx + ty*ty);
double angle = Math.acos(ty / t_length);
Then to rotate your Canvas. you can use the code
canvas.rotate(angle);
Or you can use another method as
public int touch_x,touch_y,cx,cy;
public float angle=0;
#Override
public boolean onTouchEvent(MotionEvent event) {
touch_x = (int)event.getX();
touch_y = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
}
//double tx = touch_x - cx, ty = touch_y - cy;
// double t_length = Math.sqrt(tx*tx + ty*ty);
//angle = (float) Math.acos(ty / t_length);
double dx = touch_x - cx;
// Minus to correct for coord re-mapping
double dy = -touch_y - cy;
double inRads = Math.atan2(dy,dx);
// We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
if (inRads < 0)
inRads = Math.abs(inRads);
else
inRads = 2*Math.PI - inRads;
angle= (float) Math.toDegrees(inRads);
return false;
}
I'm working on a drawing app, where the user can pan & zoom to a specific portion of the screen and start drawing with zoom applied. To be more specific, I'm looking for a way to implement zoom, pinch & pan gesture in Canvas (horizontal and vertical scrolling with moveable x, y coordinates).
Right now, I've successfully developed the zoom only feature but it's not accurate and the pan option is not working.
See my sample code here,
public class DrawingView extends View {
//canvas
private Canvas drawCanvas;
//canvas bitmap
private Bitmap canvasBitmap;
private boolean dragged = false;
private float displayWidth;
private float displayHeight;
//These two constants specify the minimum and maximum zoom
private static float MIN_ZOOM = 1f;
private static float MAX_ZOOM = 5f;
private float scaleFactor = 1.f;
private ScaleGestureDetector detector;
//These constants specify the mode that we're in
private static int NONE = 0;
private static int DRAG = 1;
private static int ZOOM = 2;
private int mode;
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
ctx = context;
setupDrawing();
}
private void setupDrawing() {
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
displayWidth = metrics.widthPixels;
displayHeight = metrics.heightPixels;
setFocusable(true);
setFocusableInTouchMode(true);
}
class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
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);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//detect user touch
float x = event.getX();
float y = event.getY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
//
downx = event.getX();
downy = event.getY();
mode = DRAG;
//We assign the current X and Y coordinate of the finger to startX and startY minus the previously translated
//amount for each coordinates This works even when we are translating the first time because the initial
//values for these two variables is zero.
startX = event.getX() - previousTranslateX;
startY = event.getY() - previousTranslateY;
break;
case MotionEvent.ACTION_MOVE:
translateX = event.getX() - startX;
translateY = event.getY() - startY;
//We cannot use startX and startY directly because we have adjusted their values using the previous translation values.
//This is why we need to add those values to startX and startY so that we can get the actual coordinates of the finger.
double distance = Math.sqrt(Math.pow(event.getX() - (startX + previousTranslateX), 2) + Math.pow(event.getY() - (startY + previousTranslateY), 2));
if (distance > 0) {
dragged = true;
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
mode = ZOOM;
break;
ase MotionEvent.ACTION_UP:
//
upx = event.getX();
upy = event.getY();
mode = NONE;
dragged = false;
//All fingers went up, so let's save the value of translateX and translateY into previousTranslateX and
//previousTranslate
previousTranslateX = translateX;
previousTranslateY = translateY;
break;
case MotionEvent.ACTION_POINTER_UP:
mode = DRAG;
//This is not strictly necessary; we save the value of translateX and translateY into previousTranslateX
//and previousTranslateY when the second finger goes up
previousTranslateX = translateX;
previousTranslateY = translateY;
break;
detector.onTouchEvent(event);
//We redraw the canvas only in the following cases:
//
// o The mode is ZOOM
// OR
// o The mode is DRAG and the scale factor is not equal to 1 (meaning we have zoomed) and dragged is
// set to true (meaning the finger has actually moved)
if ((mode == DRAG && scaleFactor != 1f && dragged) || mode == ZOOM) {
invalidate();
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
//If translateX times -1 is lesser than zero, let's set it to zero. This takes care of the left bound
if ((translateX * -1) < 0) {
translateX = 0;
}
//This is where we take care of the right bound. We compare translateX times -1 to (scaleFactor - 1) * displayWidth.
//If translateX is greater than that value, then we know that we've gone over the bound. So we set the value of
//translateX to (1 - scaleFactor) times the display width. Notice that the terms are interchanged; it's the same
//as doing -1 * (scaleFactor - 1) * displayWidth
else if ((translateX * -1) > (scaleFactor - 1) * displayWidth) {
translateX = (1 - scaleFactor) * displayWidth;
}
if (translateY * -1 < 0) {
translateY = 0;
}
//We do the exact same thing for the bottom bound, except in this case we use the height of the display
else if ((translateY * -1) > (scaleFactor - 1) * displayHeight) {
translateY = (1 - scaleFactor) * displayHeight;
}
//We need to divide by the scale factor here, otherwise we end up with excessive panning based on our zoom level
//because the translation amount also gets scaled according to how much we've zoomed into the canvas.
canvas.translate(translateX / scaleFactor, translateY / scaleFactor);
}
//We're going to scale the X and Y coordinates by the same amount
//canvas.scale(scaleFactor, scaleFactor);
canvas.scale(this.scaleFactor, this.scaleFactor, this.detector.getFocusX(), this.detector.getFocusY());
}
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;
}
}
}
I've got this canvas which the user can add images/text etc to. If the user drags one of the items to either side of the canvas, it should expand if needed. I googled, but couldn't find any reasonable solution. Also, the canvas is about 90% of the screen width, and 70% of the height.. I'm not asking for an entire solution.. I just need a tip on how to do this (Links, docs, whatever)
Well, it's difficult to guess what you're trying to achieve. When you say "it should expand if needed", what do you mean? Expand to fill the parent view? Expand to it's intrinsic size?
Here's some (incomplete) code I use in a custom view class. Most of it is gleaned from multiple solutions on here and I give thanks to the original authors. The onDraw is the most interesting one. When you want to draw (where it says custom drawing here), you don't need to worry about translation or scaling as the canvas itself is translated and scaled. In other words, your x and y co-ords are relative to the view size - simply multiply them by scale.
public class LightsViewer extends ImageView {
private float scale;
// minimum and maximum zoom
private float MIN_ZOOM = 1f;
private float MAX_ZOOM = 5f;
// mid point between fingers to centre scale
private PointF mid = new PointF();
private float scaleFactor = 1.f;
private ScaleGestureDetector detector;
// drag/zoom mode
private final static int NONE = 0;
// current mode
private int mode ;
private float startX = 0f;
private float startY = 0f;
private float translateX = 0f;
private float translateY = 0f;
private float previousTranslateX = 0f;
private float previousTranslateY = 0f;
public LightsViewer(Context context) {
super(context);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
displayWidth = display.getWidth();
displayHeight = display.getHeight();
}
public LightsViewer(Context context, AttributeSet attrs) {
super(context,attrs);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
displayWidth = display.getWidth();
displayHeight = display.getHeight();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int ZOOM = 2;
int DRAG = 1;
if (!allowZooming){return true;}
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mode = DRAG;
//We assign the current X and Y coordinate of the finger to startX and startY minus the previously translated
//amount for each coordinates This works even when we are translating the first time because the initial
//values for these two variables is zero.
startX = event.getX() - previousTranslateX;
startY = event.getY() - previousTranslateY;
break;
case MotionEvent.ACTION_MOVE:
if (mode == ZOOM){
Log.d("LIGHTS","ACTION_MOVE:Move but ZOOM, breaking");
break;}
translateX = event.getX() - startX;
translateY = event.getY() - startY;
//We cannot use startX and startY directly because we have adjusted their values using the previous translation values.
//This is why we need to add those values to startX and startY so that we can get the actual coordinates of the finger.
double distance = Math.sqrt(Math.pow(event.getX() - (startX + previousTranslateX), 2) +
Math.pow(event.getY() - (startY + previousTranslateY), 2)
);
if(distance > 0) {
dragged = true;
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
midPoint(mid, event);
mode = ZOOM;
break;
case MotionEvent.ACTION_UP:
mode = NONE;
dragged = false;
//All fingers went up, so let's save the value of translateX and translateY into previousTranslateX and
//previousTranslate
previousTranslateX = translateX;
previousTranslateY = translateY;
break;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
//This is not strictly necessary; we save the value of translateX and translateY into previousTranslateX
//and previousTranslateY when the second finger goes up
previousTranslateX = translateX;
previousTranslateY = translateY;
break;
}
detector.onTouchEvent(event);
//We redraw the canvas only in the following cases:
//
// o The mode is ZOOM
// OR
// o The mode is DRAG and the scale factor is not equal to 1 (meaning we have zoomed) and dragged is
// set to true (meaning the finger has actually moved)
if ((mode == DRAG && scaleFactor != 1f && dragged) || mode == ZOOM) {
this.invalidate();
}
return true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (this.getImageMatrix().isIdentity()){return;}
if (allowZooming){
this.applyMatrix(this.getImageMatrix());
}
}
#Override
public void onDraw(Canvas canvas) {
canvas.save();
// scale the canvas
canvas.scale(scaleFactor, scaleFactor, mid.x, mid.y);
canvas.translate(translateX / scaleFactor, translateY / scaleFactor);
super.onDraw(canvas);
// do custom drawing here...e.g.
canvas.drawCircle(100,100, 3 / scaleFactor,light.paint);
canvas.restore();
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
return true;
}
}
// calculate the mid point of the first two fingers
private void midPoint(PointF point, MotionEvent event) {
// ...
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
Log.d("LIGHTS", x/2 + "," + y/2);
}
public void setMinZoom(float minZoom){
this.MIN_ZOOM = minZoom;
}
public void applyMatrix(Matrix matrix){
float[] matrixValues = new float[9];
matrix.getValues(matrixValues);
int x = (int)matrixValues[Matrix.MTRANS_X];
int y = (int)matrixValues[Matrix.MTRANS_Y];
float scale = matrixValues[Matrix.MSCALE_X];
if (lights!=null){
for (Light light:lights){
light.setX((int)((light.originalX * scale) + x));
light.setY((int)((light.originalY * scale) + y));
}
}
// if either the x or y translations are less than 0, then the image has been cropped
// so set the min zoom to the ratio of the displayed size and the actual size of the image
if (matrixValues[Matrix.MTRANS_X] < 0 || matrixValues[Matrix.MTRANS_Y] <0){
MIN_ZOOM = displayWidth / this.getDrawable().getIntrinsicWidth();
}else{
MIN_ZOOM = 1;
}
}
public void enableZooming(boolean enable){
allowZooming = enable;
}
public void setScale(float scale){
for (Light light:lights){
light.setX((int)(light.originalX * scale));
light.setY((int)(light.originalY * scale));
}
}
}