Detecting Fling touch in App - android

I am Trying to implement a swipe touch to control the paddle in the app, I've managed to get the paddle move by detecting a single touch but I can't understand how to make a fling work. I've tried implementing ths solution by referring the official android docs but this crashes the app. Any Advice?
package com.nblsoft.pong;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class PongLogic extends View {
MainActivity mainactivity = (MainActivity) getContext();
private GestureDetectorCompat mDetector = new GestureDetectorCompat(mainactivity, new MyGestureListner());
//set screen constrains in dip
Configuration configuration = this.getResources().getConfiguration();
int dpHeight = configuration.screenHeightDp; //The current height of the available screen space, in dp units, corresponding to screen height resource qualifier.
int dpWidth = configuration.screenWidthDp; //The current width of the available screen space, in dp units, corresponding to screen width resource qualifier.
//int smallestScreenWidthDp = configuration.smallestScreenWidthDp; //The smallest screen size an application will see in normal operation, corresponding to smallest screen width resource qualifier.
//DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
//float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
//float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
private int dptopixel(int DESIRED_DP_VALUE) {
final float scale = getResources().getDisplayMetrics().density;
return (int) ((DESIRED_DP_VALUE) * scale + 0.5f);
}
private int pixeltodp(int DESIRED_PIXEL_VALUE) {
final float scale = getResources().getDisplayMetrics().density;
return (int) ((DESIRED_PIXEL_VALUE) - 0.5f / scale);
}
//set paddle size, speed, position vector
int AI_paddle_pos_x = 4 * (dptopixel(dpWidth) / 100); //3 for 320x480, 10 for 1080x1920 etc.
int paddle_width = (dptopixel(dpWidth) / 10); //
int AI_paddle_pos_y = (dptopixel(dpHeight) / 10); //48 for 320x480, 190 for 1080x1920 etc.
int paddle_height = (dptopixel(dpHeight) / 100) + 3; //the paddle is 100% of the total height of phone.
int user_paddle_pos_x = 4 * (dptopixel(dpWidth) / 100);
int user_paddle_pos_y = dptopixel(dpHeight) - ((dptopixel(dpHeight) / 10) + (dptopixel(dpHeight) / 100) + 3);
//Score
int score_user = 0;
int score_AI = 0;
//User Paddle
public Rect paddle_user = new Rect(user_paddle_pos_x,
user_paddle_pos_y,
user_paddle_pos_x + paddle_width,
user_paddle_pos_y + paddle_height);
int user_paddle_vel = 0;
//AI paddle
Rect paddle_AI = new Rect(AI_paddle_pos_x,
AI_paddle_pos_y,
AI_paddle_pos_x + paddle_width,
AI_paddle_pos_y + paddle_height);
//set ball position vector, Velocity vector, acceleration
int ball_pos_x = 0;
int ball_pos_y = (dptopixel(dpHeight) / 2);
int ball_size = dptopixel(dpWidth) / 100;
int ball_velocity_x = 1;
int ball_velocity_y = 3;
// Ball
Rect ball = new Rect(ball_pos_x,
ball_pos_y,
ball_pos_x + ball_size,
ball_pos_y + ball_size);
//Override onDraw method
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint myUI = new Paint();
myUI.setColor(Color.WHITE);
Paint myscore = new Paint();
myscore.setTextSize(dptopixel(dpWidth / 20));
myscore.setColor(Color.WHITE);
//mytext.setStyle(Paint.Style.STROKE);
//mytext.setStrokeWidth(2);
// Draw Score
canvas.drawText(Integer.toString(score_AI), (dptopixel(dpWidth) / 10), (dptopixel(dpHeight) / 4), myscore);
canvas.drawText(Integer.toString(score_user), (dptopixel(dpWidth) / 10), 3 * (dptopixel(dpHeight) / 4), myscore);
// Draw Middle point
canvas.drawRect(0, ((dptopixel(dpHeight)) / 2), (dptopixel(dpWidth)), (((dptopixel(dpHeight)) / 2) + 2), myUI);
// Draw both paddles
canvas.drawRect(paddle_user, myUI);
canvas.drawRect(paddle_AI, myUI);
// Draw ball
canvas.drawRect(ball, myUI);
//Practise Methods
//canvas.drawText(Integer.toString(dptopixel(dpHeight)),300,300,mytext);
//canvas.drawText(Integer.toString(dptopixel(dpWidth)), 400, 400, mytext);
//canvas.drawText(Integer.toString(dpHeight),500,500,mytext);
//canvas.drawText(Integer.toString(dpWidth),600,600,mytext);
//canvas.drawText("Fuck", 700, 700, mytext);
//canvas.drawRect(0,0,dptopixel(dpWidth),dptopixel(dpHeight),mytext);
//Game Loop Updater
update();
invalidate();
}
private void update() {
if(ball.centerY() < dptopixel(dpHeight)/2){ paddle_AI.offsetTo(ball.centerX()- dptopixel(10), AI_paddle_pos_y); }
if (paddle_user.contains(ball)) {
ball_velocity_y = ball_velocity_y * -1;
} else if (paddle_AI.contains(ball)) {
ball_velocity_y = ball_velocity_y * -1;
} else if ((ball.centerX() > (dptopixel(dpWidth))) || (ball.centerX() < 0)) {
ball_velocity_x = ball_velocity_x * -1;
} else if (ball.centerY() < 0) {
//Update the user score
score_user = 1 + score_user;
//re draw the ball
ball.offsetTo(0, (dptopixel(dpHeight) / 2));
} else if (ball.centerY() > (dptopixel(dpHeight))) {
//Update the AI score
score_AI = 1 + score_AI;
//re draw the ball
ball.offsetTo(0, (dptopixel(dpHeight) / 2));
}
ball.offset(ball_velocity_x, ball_velocity_y);
}
//Override Touch method
/*
//
NOT WORKING SWIPE METHODS
float x1, x2, y1, y2;
final int MIN_DISTANCE = 70;
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
y1 = event.getY();
break;
case MotionEvent.ACTION_UP:
x2 = event.getX();
y2 = event.getY();
float deltaX = x2 - x1;
float deltaY = y2 - y1;
if (deltaX > MIN_DISTANCE)
{
paddle_user.offset(1, 0);
break;
}
else if (Math.abs(deltaX) > MIN_DISTANCE)
{
paddle_user.offset(-1, 0);
break;
}
}
return true;
}*/
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
/*
if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (event.getX() > dptopixel(dpWidth) / 2) {
paddle_user.offset(10, 0);
} else {
paddle_user.offset(-10, 0);
}
}
return true;
*/
}
/* #Override
public boolean onTouch(View v, MotionEvent event) {
this.paddle_user.offsetTo(10,10);
return true; //Event Handled
}
*/
public PongLogic(Context context) {
super(context);
setBackgroundColor(Color.BLACK); //to set background
this.setFocusableInTouchMode(true); //to enable touch mode
}
class MyGestureListner extends GestureDetector.SimpleOnGestureListener{
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
if (event1.getAction() == MotionEvent.ACTION_DOWN) {
user_paddle_vel = (int) velocityX;
paddle_user.offset(user_paddle_vel,0);
}
else if(event1.getAction() == MotionEvent.ACTION_UP){
user_paddle_vel = 0;
}
return true;
}
}
}

You can take a look to my article in Medium, I explained step by step how to do it: https://medium.com/#euryperez/android-pearls-detect-swipe-and-touch-over-a-view-203ae2c028dc#.lcmg4jytc

Related

Custom Knob View for controlling Volume?

I want to show progress bar around knob. After following this tutorial I created this
knob it is working fine.
But How could i modify the above knob to look like the second image
Running code for the first knob is written below.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.MeasureSpec;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
public class RoundKnobButton extends RelativeLayout implements
OnGestureListener
{
public int eventValue=10;
//doctory starts
Paint p1,p2,p3;
RectF oval;
int width;
//doctory ends
private GestureDetector gestureDetector;
private float mAngleDown, mAngleUp;
private ImageView ivRotor;
private Bitmap bmpRotorOn, bmpRotorOff;
private boolean mState = false;
private int m_nWidth = 0, m_nHeight = 0;
public interface RoundKnobButtonListener
{
public void onStateChange(boolean newstate);
public void onRotate(int percentage);
}
private RoundKnobButtonListener m_listener;
public void SetListener(RoundKnobButtonListener l)
{
m_listener = l;
}
public void SetState(boolean state)
{
mState = state;
ivRotor.setImageBitmap(state ? bmpRotorOn : bmpRotorOff);
}
public RoundKnobButton(Context context, int back, int rotoron,
int rotoroff, final int w, final int h) {
super(context);
//doctory starts
width = w;
p1 = new Paint(1);
p1.setColor(Color.rgb(86, 86, 86));
p1.setStyle(android.graphics.Paint.Style.FILL);
p2 = new Paint(1);
p2.setColor(Color.rgb(245, 109, 89));
p2.setStyle(android.graphics.Paint.Style.FILL);
p3 = new Paint(1);
p3.setColor(Color.GREEN);
p3.setStyle(android.graphics.Paint.Style.STROKE);
oval = new RectF();
//doctory ends...
// we won't wait for our size to be calculated, we'll just store out
// fixed size
m_nWidth = w;
m_nHeight = h;
// create stator
ImageView ivBack = new ImageView(context);
ivBack.setImageResource(back);
RelativeLayout.LayoutParams lp_ivBack = new RelativeLayout.LayoutParams(
w, h);
lp_ivBack.addRule(RelativeLayout.CENTER_IN_PARENT);
addView(ivBack, lp_ivBack);
// load rotor images
Bitmap srcon = BitmapFactory.decodeResource(context.getResources(),
rotoron);
Bitmap srcoff = BitmapFactory.decodeResource(context.getResources(),
rotoroff);
float scaleWidth = ((float) w) / srcon.getWidth();
float scaleHeight = ((float) h) / srcon.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
bmpRotorOn = Bitmap.createBitmap(srcon, 0, 0, srcon.getWidth(),
srcon.getHeight(), matrix, true);
bmpRotorOff = Bitmap.createBitmap(srcoff, 0, 0, srcoff.getWidth(),
srcoff.getHeight(), matrix, true);
// create rotor
ivRotor = new ImageView(context);
ivRotor.setImageBitmap(bmpRotorOn);
RelativeLayout.LayoutParams lp_ivKnob = new RelativeLayout.LayoutParams(
w, h);// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp_ivKnob.addRule(RelativeLayout.CENTER_IN_PARENT);
addView(ivRotor, lp_ivKnob);
// set initial state
SetState(mState);
// enable gesture detector
gestureDetector = new GestureDetector(getContext(), this);
}
/**
* math..
*
* #param x
* #param y
* #return
*/
private float cartesianToPolar(float x, float y) {
return (float) -Math.toDegrees(Math.atan2(x - 0.5f, y - 0.5f));
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else
return super.onTouchEvent(event);
}
public boolean onDown(MotionEvent event)
{
float x = event.getX() / ((float) getWidth());
float y = event.getY() / ((float) getHeight());
mAngleDown = cartesianToPolar(1 - x, 1 - y);// 1- to correct our custom
// axis direction
return true;
}
public boolean onSingleTapUp(MotionEvent e)
{
float x = e.getX() / ((float) getWidth());
float y = e.getY() / ((float) getHeight());
mAngleUp = cartesianToPolar(1 - x, 1 - y);// 1- to correct our custom
// axis direction
// if we click up the same place where we clicked down, it's just a
// button press
if (!Float.isNaN(mAngleDown) && !Float.isNaN(mAngleUp)
&& Math.abs(mAngleUp - mAngleDown) < 10) {
SetState(!mState);
if (m_listener != null)
m_listener.onStateChange(mState);
}
return true;
}
public void setRotorPosAngle(float deg)
{
if (deg >= 210 || deg <= 150)
{
if (deg > 180)
deg = deg - 360;
Matrix matrix = new Matrix();
ivRotor.setScaleType(ScaleType.MATRIX);
// matrix.postRotate((float) deg, 210 / 2, 210 / 2);// getWidth()/2,
// getHeight()/2);
matrix.postRotate((float) deg, m_nWidth/2, m_nHeight/2);//getWidth()/2, getHeight()/2);
ivRotor.setImageMatrix(matrix);
}
}
public void setRotorPercentage(int percentage)
{
int posDegree = percentage * 3 - 150;
if (posDegree < 0)
posDegree = 360 + posDegree;
setRotorPosAngle(posDegree);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
float x = e2.getX() / ((float) getWidth());
float y = e2.getY() / ((float) getHeight());
float rotDegrees = cartesianToPolar(1 - x, 1 - y);// 1- to correct our
// custom axis
// direction
if (!Float.isNaN(rotDegrees)) {
// instead of getting 0-> 180, -180 0 , we go for 0 -> 360
float posDegrees = rotDegrees;
if (rotDegrees < 0)
posDegrees = 360 + rotDegrees;
// deny full rotation, start start and stop point, and get a linear
// scale
if (posDegrees > 210 || posDegrees < 150) {
// rotate our imageview
setRotorPosAngle(posDegrees);
// get a linear scale
float scaleDegrees = rotDegrees + 150; // given the current
// parameters, we go
// from 0 to 300
// get position percent
int percent = (int) (scaleDegrees / 3);
if (m_listener != null)
m_listener.onRotate(percent);
return true; // consumed
} else
return false;
} else
return false; // not consumed
}
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
return false;
}
public void onLongPress(MotionEvent e) {
}
/*#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int i = width / 4;
oval.set(i - i / 2, i / 2, i * 3 + i / 2, i * 3 + i / 2);
canvas.drawOval(oval, p1);
canvas.drawArc(oval, -90F, (int)Math.round((360D * Double.valueOf(eventValue).doubleValue()) / 100D), true, p2);
canvas.drawLine(20, 30, 120, 200, p2);
}*/
/*#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int desiredWidth = width;
int desiredHeight = width;
int widthMode = android.view.View.MeasureSpec.getMode(widthMeasureSpec);
int widthSize = android.view.View.MeasureSpec.getSize(widthMeasureSpec);
int heightMode = android.view.View.MeasureSpec.getMode(heightMeasureSpec);
int heightSize = android.view.View.MeasureSpec.getSize(heightMeasureSpec);
int measuredWidth;
int measuredHeight;
if (widthMode == MeasureSpec.EXACTLY)
{
measuredWidth = widthSize ;
}
else if (widthMode == MeasureSpec.AT_MOST)
{
measuredWidth = Math.min(desiredWidth , widthSize);
}
else
{
measuredWidth = desiredWidth;
}
if (heightMode == MeasureSpec.EXACTLY)
{
measuredHeight = heightSize ;
}
else if (heightMode == MeasureSpec.AT_MOST)
{
measuredHeight = Math.min(desiredHeight, heightSize );
}
else
{
measuredHeight = desiredHeight;
}
setMeasuredDimension(measuredWidth, measuredHeight);
}
*/
}
I have created onDraw and onMeasure function function and try to draw outer progress, or how could i modify it.
Edit
Is it possible to change the rotation percentage to 20 . I mean it shows progress form 0 to 99. is it possible to convert it to 0 to 12.
Use two XML files.
circular_progress_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="1dp">
<gradient
android:angle="0"
android:endColor="#22FA05"
android:startColor="#22FA05"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
and background_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring"
android:innerRadiusRatio="2.5"
android:thickness="1dp"
android:useLevel="false">
<solid android:color="#000000" />
</shape>
and finally
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="250dp"
android:layout_height="250dp"
android:indeterminate="false"
android:progressDrawable="#drawable/circular_progress_drawable"
android:background="#drawable/background_circle"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:progress="25" />
Note that set width and height based on the image position you have

Using Rebound API with ImageView

I am currently in need of making ChatHeads like Facebook. Following the tutorials I found, I can make a ChatHead start from Service. However, when I added Rebound API from Facebook to make it smooth, I created a customized view like this post: Adding natural dragging effect to ImageView same as Facebook Messanger chat heads using Rebound library ;
but it seems to block every background touch. I can only drag the ChatHead around without able to touch anything else. How can I make a ChatHead that is still smooth draggable and also can interact with the background also (just the same as Facebook)? Any help is appreciated.
Thanks in advanced
BTW, this is my view
class ChatHeadView extends View implements SpringListener, SpringSystemListener {
private Spring xSpring;
private Spring ySpring;
private SpringSystem springSystem;
private final SpringConfig COASTING;
private float x;
private float y;
private boolean dragging;
private float radius = 100;
private float downX;
private float downY;
private float lastX;
private float lastY;
private VelocityTracker velocityTracker;
private float centerX;
private float centerY;
int screenWidth, screenHeight;
private Paint mPaint = new Paint();
private Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
public ChatHeadView(Context context, int width, int height) {
super(context);
springSystem = SpringSystem.create();
springSystem.addListener(this);
COASTING = SpringConfig.fromOrigamiTensionAndFriction(0, 0.5);
COASTING.tension = 0;
xSpring = springSystem.createSpring();
ySpring = springSystem.createSpring();
xSpring.addListener(this);
ySpring.addListener(this);
getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
centerX = getWidth() / 2f;
centerY = getHeight() / 2f;
xSpring.setCurrentValue(centerX).setAtRest();
ySpring.setCurrentValue(centerY).setAtRest();
getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
}
});
screenWidth = width;
screenHeight = height;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mBitmap, x - mBitmap.getWidth() / 2,
y - mBitmap.getHeight(), mPaint);
}
#SuppressLint("Recycle")
#Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getRawX();
float touchY = event.getRawY();
boolean ret = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = touchX;
downY = touchY;
lastX = downX;
lastY = downY;
velocityTracker = VelocityTracker.obtain();
velocityTracker.addMovement(event);
if (downX > x - radius && downX < x + radius && downY > y - radius
&& downY < y + radius) {
dragging = true;
ret = true;
}
break;
case MotionEvent.ACTION_MOVE:
if (!dragging) {
break;
}
velocityTracker.addMovement(event);
float offsetX = lastX - touchX;
float offsetY = lastY - touchY;
xSpring.setCurrentValue(xSpring.getCurrentValue() - offsetX)
.setAtRest();
ySpring.setCurrentValue(ySpring.getCurrentValue() - offsetY)
.setAtRest();
checkConstraints();
ret = true;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (!dragging) {
break;
}
velocityTracker.addMovement(event);
velocityTracker.computeCurrentVelocity(1000);
dragging = false;
ySpring.setSpringConfig(COASTING);
xSpring.setSpringConfig(COASTING);
downX = 0;
downY = 0;
xSpring.setVelocity(velocityTracker.getXVelocity());
ySpring.setVelocity(velocityTracker.getYVelocity());
ret = true;
}
lastX = touchX;
lastY = touchY;
return ret;
}
#Override
public void onSpringUpdate(Spring s) {
x = (float) xSpring.getCurrentValue();
y = (float) ySpring.getCurrentValue();
invalidate();
}
#Override
public void onSpringActivate(Spring s) {
}
#Override
public void onSpringAtRest(Spring s) {
}
#Override
public void onSpringEndStateChange(Spring s) {
}
#Override
public void onBeforeIntegrate(BaseSpringSystem springSystem) {
}
#Override
public void onAfterIntegrate(BaseSpringSystem springSystem) {
checkConstraints();
}
private void checkConstraints() {
if (x + radius >= screenWidth) {
xSpring.setVelocity(-xSpring.getVelocity());
xSpring.setCurrentValue(xSpring.getCurrentValue()
- (x + radius - screenWidth), false);
}
if (x - radius <= 0) {
xSpring.setVelocity(-xSpring.getVelocity());
xSpring.setCurrentValue(xSpring.getCurrentValue() - (x - radius),
false);
}
if (y + radius >= screenHeight) {
ySpring.setVelocity(-ySpring.getVelocity());
ySpring.setCurrentValue(ySpring.getCurrentValue()
- (y + radius - screenHeight), false);
}
if (y - radius <= 0) {
ySpring.setVelocity(-ySpring.getVelocity());
ySpring.setCurrentValue(ySpring.getCurrentValue() - (y - radius),
false);
}
}
}
this is where I add View with WindowManager:
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
chatHeadView = new ChatHeadView(this, screenWidth, screenHeight);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, PixelFormat.TRANSLUCENT);
windowManager.addView(chatHeadView, params);
In the documentation WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
Window flag: even when this window is focusable (its FLAG_NOT_FOCUSABLE is not set), allow any pointer events outside of the window to be sent to the windows behind it. Otherwise it will consume all pointer events itself, regardless of whether they are inside of the window.
It's saying about your problem.
Instead, try WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE flag.
you can get TouchEvent on the view and it won't consume other events.

How to hide Actionbar when touch on custom Imageview

I am using Custom Image view posted on git hub by Michael Ortiz. Now I want to disappear action bar when user simply touch on image view and again to be appear when user raised up his finger. Note that this custom image view has functionality of double tap zoom, pinch zoom and fling it has implemented gesture detector
Now how can achieve my desired functionality with this ready custom image view
Here is code for custom Image View
public class TouchImageView extends ImageView {
private static final String DEBUG = "DEBUG";
private ZoomImageActivity zoomActivity=new ZoomImageActivity();
//
// SuperMin and SuperMax multipliers. Determine how much the image can be
// zoomed below or above the zoom boundaries, before animating back to the
// min/max zoom boundary.
//
private static final float SUPER_MIN_MULTIPLIER = .75f;
private static final float SUPER_MAX_MULTIPLIER = 1.25f;
//
// Scale of image ranges from minScale to maxScale, where minScale == 1
// when the image is stretched to fit view.
//
private float normalizedScale;
//
// Matrix applied to image. MSCALE_X and MSCALE_Y should always be equal.
// MTRANS_X and MTRANS_Y are the other values used. prevMatrix is the matrix
// saved prior to the screen rotating.
//
private Matrix matrix, prevMatrix;
public static enum State { NONE, DRAG, ZOOM, FLING, ANIMATE_ZOOM };
private State state;
private float minScale;
private float maxScale;
private float superMinScale;
private float superMaxScale;
private float[] m;
private Context context;
private Fling fling;
//
// Size of view and previous view size (ie before rotation)
//
private int viewWidth, viewHeight, prevViewWidth, prevViewHeight;
//
// Size of image when it is stretched to fit view. Before and After rotation.
//
private float matchViewWidth, matchViewHeight, prevMatchViewWidth, prevMatchViewHeight;
//
// After setting image, a value of true means the new image should maintain
// the zoom of the previous image. False means it should be resized within the view.
//
private boolean maintainZoomAfterSetImage;
//
// True when maintainZoomAfterSetImage has been set to true and setImage has been called.
//
private boolean setImageCalledRecenterImage;
private ScaleGestureDetector mScaleDetector;
private GestureDetector mGestureDetector;
public TouchImageView(Context context) {
super(context);
sharedConstructing(context);
}
public TouchImageView(Context context, AttributeSet attrs) {
super(context, attrs);
sharedConstructing(context);
}
public TouchImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
sharedConstructing(context);
}
private void sharedConstructing(Context context) {
super.setClickable(true);
this.context = context;
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
mGestureDetector = new GestureDetector(context, new GestureListener());
matrix = new Matrix();
prevMatrix = new Matrix();
m = new float[9];
normalizedScale = 1;
minScale = 1;
maxScale = 3;
superMinScale = SUPER_MIN_MULTIPLIER * minScale;
superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
maintainZoomAfterSetImage = true;
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
setState(NONE);
setOnTouchListener(new TouchImageViewListener());
}
#Override
public void setImageResource(int resId) {
super.setImageResource(resId);
setImageCalled();
savePreviousImageValues();
fitImageToView();
}
#Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
setImageCalled();
savePreviousImageValues();
fitImageToView();
}
#Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
setImageCalled();
savePreviousImageValues();
fitImageToView();
}
#Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
setImageCalled();
savePreviousImageValues();
fitImageToView();
}
private void setImageCalled() {
if (!maintainZoomAfterSetImage) {
setImageCalledRecenterImage = true;
}
}
/**
* Save the current matrix and view dimensions
* in the prevMatrix and prevView variables.
*/
private void savePreviousImageValues() {
if (matrix != null) {
matrix.getValues(m);
prevMatrix.setValues(m);
prevMatchViewHeight = matchViewHeight;
prevMatchViewWidth = matchViewWidth;
prevViewHeight = viewHeight;
prevViewWidth = viewWidth;
}
}
#Override
public Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable("instanceState", super.onSaveInstanceState());
bundle.putFloat("saveScale", normalizedScale);
bundle.putFloat("matchViewHeight", matchViewHeight);
bundle.putFloat("matchViewWidth", matchViewWidth);
bundle.putInt("viewWidth", viewWidth);
bundle.putInt("viewHeight", viewHeight);
matrix.getValues(m);
bundle.putFloatArray("matrix", m);
return bundle;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
normalizedScale = bundle.getFloat("saveScale");
m = bundle.getFloatArray("matrix");
prevMatrix.setValues(m);
prevMatchViewHeight = bundle.getFloat("matchViewHeight");
prevMatchViewWidth = bundle.getFloat("matchViewWidth");
prevViewHeight = bundle.getInt("viewHeight");
prevViewWidth = bundle.getInt("viewWidth");
super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
return;
}
super.onRestoreInstanceState(state);
}
/**
* Get the max zoom multiplier.
* #return max zoom multiplier.
*/
public float getMaxZoom() {
return maxScale;
}
/**
* Set the max zoom multiplier. Default value: 3.
* #param max max zoom multiplier.
*/
public void setMaxZoom(float max) {
maxScale = max;
superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
}
/**
* Get the min zoom multiplier.
* #return min zoom multiplier.
*/
public float getMinZoom() {
return minScale;
}
/**
* After setting image, a value of true means the new image should maintain
* the zoom of the previous image. False means the image should be resized within
* the view. Defaults value is true.
* #param maintainZoom
*/
public void maintainZoomAfterSetImage(boolean maintainZoom) {
maintainZoomAfterSetImage = maintainZoom;
}
/**
* Get the current zoom. This is the zoom relative to the initial
* scale, not the original resource.
* #return current zoom multiplier.
*/
public float getCurrentZoom() {
return normalizedScale;
}
/**
* Set the min zoom multiplier. Default value: 1.
* #param min min zoom multiplier.
*/
public void setMinZoom(float min) {
minScale = min;
superMinScale = SUPER_MIN_MULTIPLIER * minScale;
}
/**
* For a given point on the view (ie, a touch event), returns the
* point relative to the original drawable's coordinate system.
* #param x
* #param y
* #return PointF relative to original drawable's coordinate system.
*/
public PointF getDrawablePointFromTouchPoint(float x, float y) {
return transformCoordTouchToBitmap(x, y, true);
}
/**
* For a given point on the view (ie, a touch event), returns the
* point relative to the original drawable's coordinate system.
* #param p
* #return PointF relative to original drawable's coordinate system.
*/
public PointF getDrawablePointFromTouchPoint(PointF p) {
return transformCoordTouchToBitmap(p.x, p.y, true);
}
/**
* Performs boundary checking and fixes the image matrix if it
* is out of bounds.
*/
private void fixTrans() {
matrix.getValues(m);
float transX = m[Matrix.MTRANS_X];
float transY = m[Matrix.MTRANS_Y];
float fixTransX = getFixTrans(transX, viewWidth, getImageWidth());
float fixTransY = getFixTrans(transY, viewHeight, getImageHeight());
if (fixTransX != 0 || fixTransY != 0) {
matrix.postTranslate(fixTransX, fixTransY);
}
}
/**
* When transitioning from zooming from focus to zoom from center (or vice versa)
* the image can become unaligned within the view. This is apparent when zooming
* quickly. When the content size is less than the view size, the content will often
* be centered incorrectly within the view. fixScaleTrans first calls fixTrans() and
* then makes sure the image is centered correctly within the view.
*/
private void fixScaleTrans() {
fixTrans();
matrix.getValues(m);
if (getImageWidth() < viewWidth) {
m[Matrix.MTRANS_X] = (viewWidth - getImageWidth()) / 2;
}
if (getImageHeight() < viewHeight) {
m[Matrix.MTRANS_Y] = (viewHeight - getImageHeight()) / 2;
}
matrix.setValues(m);
}
private float getFixTrans(float trans, float viewSize, float contentSize) {
float minTrans, maxTrans;
if (contentSize <= viewSize) {
minTrans = 0;
maxTrans = viewSize - contentSize;
} else {
minTrans = viewSize - contentSize;
maxTrans = 0;
}
if (trans < minTrans)
return -trans + minTrans;
if (trans > maxTrans)
return -trans + maxTrans;
return 0;
}
private float getFixDragTrans(float delta, float viewSize, float contentSize) {
if (contentSize <= viewSize) {
return 0;
}
return delta;
}
private float getImageWidth() {
return matchViewWidth * normalizedScale;
}
private float getImageHeight() {
return matchViewHeight * normalizedScale;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drawable = getDrawable();
if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
setMeasuredDimension(0, 0);
return;
}
int drawableWidth = drawable.getIntrinsicWidth();
int drawableHeight = drawable.getIntrinsicHeight();
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
viewWidth = setViewSize(widthMode, widthSize, drawableWidth);
viewHeight = setViewSize(heightMode, heightSize, drawableHeight);
//
// Set view dimensions
//
setMeasuredDimension(viewWidth, viewHeight);
//
// Fit content within view
//
fitImageToView();
}
/**
* If the normalizedScale is equal to 1, then the image is made to fit the screen. Otherwise,
* it is made to fit the screen according to the dimensions of the previous image matrix. This
* allows the image to maintain its zoom after rotation.
*/
private void fitImageToView() {
Drawable drawable = getDrawable();
if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
return;
}
if (matrix == null || prevMatrix == null) {
return;
}
int drawableWidth = drawable.getIntrinsicWidth();
int drawableHeight = drawable.getIntrinsicHeight();
//
// Scale image for view
//
float scaleX = (float) viewWidth / drawableWidth;
float scaleY = (float) viewHeight / drawableHeight;
float scale = Math.min(scaleX, scaleY);
//
// Center the image
//
float redundantYSpace = viewHeight - (scale * drawableHeight);
float redundantXSpace = viewWidth - (scale * drawableWidth);
matchViewWidth = viewWidth - redundantXSpace;
matchViewHeight = viewHeight - redundantYSpace;
if (normalizedScale == 1 || setImageCalledRecenterImage) {
//
// Stretch and center image to fit view
//
matrix.setScale(scale, scale);
matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
normalizedScale = 1;
setImageCalledRecenterImage = false;
} else {
prevMatrix.getValues(m);
//
// Rescale Matrix after rotation
//
m[Matrix.MSCALE_X] = matchViewWidth / drawableWidth * normalizedScale;
m[Matrix.MSCALE_Y] = matchViewHeight / drawableHeight * normalizedScale;
//
// TransX and TransY from previous matrix
//
float transX = m[Matrix.MTRANS_X];
float transY = m[Matrix.MTRANS_Y];
//
// Width
//
float prevActualWidth = prevMatchViewWidth * normalizedScale;
float actualWidth = getImageWidth();
translateMatrixAfterRotate(Matrix.MTRANS_X, transX, prevActualWidth, actualWidth, prevViewWidth, viewWidth, drawableWidth);
//
// Height
//
float prevActualHeight = prevMatchViewHeight * normalizedScale;
float actualHeight = getImageHeight();
translateMatrixAfterRotate(Matrix.MTRANS_Y, transY, prevActualHeight, actualHeight, prevViewHeight, viewHeight, drawableHeight);
//
// Set the matrix to the adjusted scale and translate values.
//
matrix.setValues(m);
}
setImageMatrix(matrix);
}
/**
* Set view dimensions based on layout params
*
* #param mode
* #param size
* #param drawableWidth
* #return
*/
private int setViewSize(int mode, int size, int drawableWidth) {
int viewSize;
switch (mode) {
case MeasureSpec.EXACTLY:
viewSize = size;
break;
case MeasureSpec.AT_MOST:
viewSize = Math.min(drawableWidth, size);
break;
case MeasureSpec.UNSPECIFIED:
viewSize = drawableWidth;
break;
default:
viewSize = size;
break;
}
return viewSize;
}
private void translateMatrixAfterRotate(int axis, float trans, float prevImageSize, float imageSize, int prevViewSize, int viewSize, int drawableSize) {
if (imageSize < viewSize) {
//
// The width/height of image is less than the view's width/height. Center it.
//
m[axis] = (viewSize - (drawableSize * m[Matrix.MSCALE_X])) * 0.5f;
} else if (trans > 0) {
//
// The image is larger than the view, but was not before rotation. Center it.
//
m[axis] = -((imageSize - viewSize) * 0.5f);
} else {
//
// Find the area of the image which was previously centered in the view. Determine its distance
// from the left/top side of the view as a fraction of the entire image's width/height. Use that percentage
// to calculate the trans in the new view width/height.
//
float percentage = (Math.abs(trans) + (0.5f * prevViewSize)) / prevImageSize;
m[axis] = -((percentage * imageSize) - (viewSize * 0.5f));
}
}
private void setState(State state) {
this.state = state;
}
/**
* Gesture Listener detects a single click or long click and passes that on
* to the view's listener.
* #author Ortiz
*
*/
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e)
{
return performClick();
}
#Override
public void onLongPress(MotionEvent e)
{
performLongClick();
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
if (fling != null) {
//
// If a previous fling is still active, it should be cancelled so that two flings
// are not run simultaenously.
//
fling.cancelFling();
}
fling = new Fling((int) velocityX, (int) velocityY);
compatPostOnAnimation(fling);
return super.onFling(e1, e2, velocityX, velocityY);
}
#Override
public boolean onDoubleTap(MotionEvent e) {
boolean consumed = false;
if (state == NONE) {
float targetZoom = (normalizedScale == minScale) ? maxScale : minScale;
DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, e.getX(), e.getY(), false);
compatPostOnAnimation(doubleTap);
consumed = true;
}
return consumed;
}
}
/**
* Responsible for all touch events. Handles the heavy lifting of drag and also sends
* touch events to Scale Detector and Gesture Detector.
* #author Ortiz
*
*/
private class TouchImageViewListener implements OnTouchListener {
//
// Remember last point position for dragging
//
private PointF last = new PointF();
#Override
public boolean onTouch(View v, MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mGestureDetector.onTouchEvent(event);
PointF curr = new PointF(event.getX(), event.getY());
if (state == NONE || state == DRAG || state == FLING) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
last.set(curr);
if (fling != null)
fling.cancelFling();
setState(DRAG);
break;
case MotionEvent.ACTION_MOVE:
if (state == DRAG) {
float deltaX = curr.x - last.x;
float deltaY = curr.y - last.y;
float fixTransX = getFixDragTrans(deltaX, viewWidth, getImageWidth());
float fixTransY = getFixDragTrans(deltaY, viewHeight, getImageHeight());
matrix.postTranslate(fixTransX, fixTransY);
fixTrans();
last.set(curr.x, curr.y);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
setState(NONE);
break;
}
}
setImageMatrix(matrix);
//
// indicate event was handled
//
return true;
}
}
/**
* ScaleListener detects user two finger scaling and scales image.
* #author Ortiz
*
*/
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
setState(ZOOM);
return true;
}
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleImage(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY(), true);
return true;
}
#Override
public void onScaleEnd(ScaleGestureDetector detector) {
super.onScaleEnd(detector);
setState(NONE);
boolean animateToZoomBoundary = false;
float targetZoom = normalizedScale;
if (normalizedScale > maxScale) {
targetZoom = maxScale;
animateToZoomBoundary = true;
} else if (normalizedScale < minScale) {
targetZoom = minScale;
animateToZoomBoundary = true;
}
if (animateToZoomBoundary) {
DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, viewWidth / 2, viewHeight / 2, true);
compatPostOnAnimation(doubleTap);
}
}
}
private void scaleImage(float deltaScale, float focusX, float focusY, boolean stretchImageToSuper) {
float lowerScale, upperScale;
if (stretchImageToSuper) {
lowerScale = superMinScale;
upperScale = superMaxScale;
} else {
lowerScale = minScale;
upperScale = maxScale;
}
float origScale = normalizedScale;
normalizedScale *= deltaScale;
if (normalizedScale > upperScale) {
normalizedScale = upperScale;
deltaScale = upperScale / origScale;
} else if (normalizedScale < lowerScale) {
normalizedScale = lowerScale;
deltaScale = lowerScale / origScale;
}
matrix.postScale(deltaScale, deltaScale, focusX, focusY);
fixScaleTrans();
}
/**
* DoubleTapZoom calls a series of runnables which apply
* an animated zoom in/out graphic to the image.
* #author Ortiz
*
*/
private class DoubleTapZoom implements Runnable {
private long startTime;
private static final float ZOOM_TIME = 500;
private float startZoom, targetZoom;
private float bitmapX, bitmapY;
private boolean stretchImageToSuper;
private AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator();
private PointF startTouch;
private PointF endTouch;
DoubleTapZoom(float targetZoom, float focusX, float focusY, boolean stretchImageToSuper) {
setState(ANIMATE_ZOOM);
startTime = System.currentTimeMillis();
this.startZoom = normalizedScale;
this.targetZoom = targetZoom;
this.stretchImageToSuper = stretchImageToSuper;
PointF bitmapPoint = transformCoordTouchToBitmap(focusX, focusY, false);
this.bitmapX = bitmapPoint.x;
this.bitmapY = bitmapPoint.y;
//
// Used for translating image during scaling
//
startTouch = transformCoordBitmapToTouch(bitmapX, bitmapY);
endTouch = new PointF(viewWidth / 2, viewHeight / 2);
}
#Override
public void run() {
float t = interpolate();
float deltaScale = calculateDeltaScale(t);
scaleImage(deltaScale, bitmapX, bitmapY, stretchImageToSuper);
translateImageToCenterTouchPosition(t);
fixScaleTrans();
setImageMatrix(matrix);
if (t < 1f) {
//
// We haven't finished zooming
//
compatPostOnAnimation(this);
} else {
//
// Finished zooming
//
setState(NONE);
}
}
/**
* Interpolate between where the image should start and end in order to translate
* the image so that the point that is touched is what ends up centered at the end
* of the zoom.
* #param t
*/
private void translateImageToCenterTouchPosition(float t) {
float targetX = startTouch.x + t * (endTouch.x - startTouch.x);
float targetY = startTouch.y + t * (endTouch.y - startTouch.y);
PointF curr = transformCoordBitmapToTouch(bitmapX, bitmapY);
matrix.postTranslate(targetX - curr.x, targetY - curr.y);
}
/**
* Use interpolator to get t
* #return
*/
private float interpolate() {
long currTime = System.currentTimeMillis();
float elapsed = (currTime - startTime) / ZOOM_TIME;
elapsed = Math.min(1f, elapsed);
return interpolator.getInterpolation(elapsed);
}
/**
* Interpolate the current targeted zoom and get the delta
* from the current zoom.
* #param t
* #return
*/
private float calculateDeltaScale(float t) {
float zoom = startZoom + t * (targetZoom - startZoom);
return zoom / normalizedScale;
}
}
/**
* This function will transform the coordinates in the touch event to the coordinate
* system of the drawable that the imageview contain
* #param x x-coordinate of touch event
* #param y y-coordinate of touch event
* #param clipToBitmap Touch event may occur within view, but outside image content. True, to clip return value
* to the bounds of the bitmap size.
* #return Coordinates of the point touched, in the coordinate system of the original drawable.
*/
private PointF transformCoordTouchToBitmap(float x, float y, boolean clipToBitmap) {
matrix.getValues(m);
float origW = getDrawable().getIntrinsicWidth();
float origH = getDrawable().getIntrinsicHeight();
float transX = m[Matrix.MTRANS_X];
float transY = m[Matrix.MTRANS_Y];
float finalX = ((x - transX) * origW) / getImageWidth();
float finalY = ((y - transY) * origH) / getImageHeight();
if (clipToBitmap) {
finalX = Math.min(Math.max(x, 0), origW);
finalY = Math.min(Math.max(y, 0), origH);
}
return new PointF(finalX , finalY);
}
/**
* Inverse of transformCoordTouchToBitmap. This function will transform the coordinates in the
* drawable's coordinate system to the view's coordinate system.
* #param bx x-coordinate in original bitmap coordinate system
* #param by y-coordinate in original bitmap coordinate system
* #return Coordinates of the point in the view's coordinate system.
*/
private PointF transformCoordBitmapToTouch(float bx, float by) {
matrix.getValues(m);
float origW = getDrawable().getIntrinsicWidth();
float origH = getDrawable().getIntrinsicHeight();
float px = bx / origW;
float py = by / origH;
float finalX = m[Matrix.MTRANS_X] + getImageWidth() * px;
float finalY = m[Matrix.MTRANS_Y] + getImageHeight() * py;
return new PointF(finalX , finalY);
}
/**
* Fling launches sequential runnables which apply
* the fling graphic to the image. The values for the translation
* are interpolated by the Scroller.
* #author Ortiz
*
*/
private class Fling implements Runnable {
Scroller scroller;
int currX, currY;
Fling(int velocityX, int velocityY) {
setState(FLING);
scroller = new Scroller(context);
matrix.getValues(m);
int startX = (int) m[Matrix.MTRANS_X];
int startY = (int) m[Matrix.MTRANS_Y];
int minX, maxX, minY, maxY;
if (getImageWidth() > viewWidth) {
minX = viewWidth - (int) getImageWidth();
maxX = 0;
} else {
minX = maxX = startX;
}
if (getImageHeight() > viewHeight) {
minY = viewHeight - (int) getImageHeight();
maxY = 0;
} else {
minY = maxY = startY;
}
scroller.fling(startX, startY, (int) velocityX, (int) velocityY, minX,
maxX, minY, maxY);
currX = startX;
currY = startY;
}
public void cancelFling() {
if (scroller != null) {
setState(NONE);
scroller.forceFinished(true);
}
}
#Override
public void run() {
if (scroller.isFinished()) {
scroller = null;
return;
}
if (scroller.computeScrollOffset()) {
int newX = scroller.getCurrX();
int newY = scroller.getCurrY();
int transX = newX - currX;
int transY = newY - currY;
currX = newX;
currY = newY;
matrix.postTranslate(transX, transY);
fixTrans();
setImageMatrix(matrix);
compatPostOnAnimation(this);
}
}
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void compatPostOnAnimation(Runnable runnable) {
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
postOnAnimation(runnable);
} else {
postDelayed(runnable, 1000/60);
}
}
private void printMatrixInfo() {
matrix.getValues(m);
Log.d(DEBUG, "Scale: " + m[Matrix.MSCALE_X] + " TransX: " + m[Matrix.MTRANS_X] + " TransY: " + m[Matrix.MTRANS_Y]);
}
}
It is definitely doable, an imageView is not the best place to act on the actionBar (a view should not have this kind of responsibility), but you can send a callback to a parent fragment or activity and do:
private void setActionBarVisibility(boolean isVisible) {
ActionBarActivity activity = (ActionBarActivity) getActivity();
if (activity != null) {
final ActionBar ab = activity.getSupportActionBar();
if (ab != null) {
if (isVisible) {
ab.show();
}
else {
ab.hide();
}
}
}
}
I solve my problem by using library project posted on https://github.com/jasonpolites/gesture-imageview/commits/master
I just add onClick listener on custom ImageView to hide and show ActionBar
You can not hide title bar on click event. You can hide it only by following method,
First Method
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
Second Method via AndroidManifest.xml
<activity android:name=".ActivityName"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>

rotate dial in limited degrees

All I want rotate image in particular angle as like below image. I have code for rotation but it rotate 360 degree but I want it only for particular degrees and get the selected number which is upper side of dial.
below is my code.
My custom View this work fine but lake of perfomance.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class MyDialView extends View implements OnGestureListener{
private static Bitmap bimmap;
private static Paint paint;
private static Rect bounds;
private int totalNicks = 100;
private int currentNick = 0;
private GestureDetector gestureDetector;
private float dragStartDeg = Float.NaN;
float dialerWidth = 0,dialerHeight = 0;
private static Paint createDefaultPaint() {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
return paint;
}
private float xyToDegrees(float x, float y) {
float distanceFromCenter = PointF.length((x - 0.5f), (y - 0.5f));
if (distanceFromCenter < 0.1f
|| distanceFromCenter > 0.5f) { // ignore center and out of bounds events
return Float.NaN;
} else {
return (float) Math.toDegrees(Math.atan2(x - 0.5f, y - 0.5f));
}
}
public final float getRotationInDegrees() {
return (360.0f / totalNicks) * currentNick;
}
public final void rotate(int nicks) {
currentNick = (currentNick + nicks);
if (currentNick >= totalNicks) {
currentNick %= totalNicks;
} else if (currentNick < 0) {
currentNick = (totalNicks + currentNick);
}
Log.e("Current nick", String.valueOf(currentNick));
if((currentNick > 80 || currentNick < 20)){
invalidate();
}
}
public MyDialView(Context context, AttributeSet attrs) {
super(context, attrs);
bimmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.out_round);
paint = createDefaultPaint();
gestureDetector = new GestureDetector(getContext(), this);
dialerWidth = bimmap.getWidth() /2.0f;
dialerHeight = bimmap.getHeight() / 2.0f;
bounds = new Rect();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.getClipBounds(bounds);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
//{
canvas.translate(bounds.left, bounds.top);
float rotation = getRotationInDegrees();
canvas.rotate(rotation, dialerWidth, dialerHeight);
canvas.drawBitmap(bimmap, 0,0,null);
//canvas.rotate(- rotation, dialerWidth, dialerHeight);
//}
canvas.restore();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
} else {
return super.onTouchEvent(event);
}
}
//Gesture detector methods
#Override
public boolean onDown(MotionEvent e) {
float x = e.getX() / ((float) getWidth());
float y = e.getY() / ((float) getHeight());
dragStartDeg = xyToDegrees(x, y);
//Log.d("deg = " , ""+dragStartDeg);
if (! Float.isNaN(dragStartDeg)) {
return true;
} else {
return false;
}
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false;
}
#Override
public void onLongPress(MotionEvent e) {
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
if (! Float.isNaN(dragStartDeg)) {
float currentDeg = xyToDegrees(e2.getX() / getWidth(),
e2.getY() / getHeight());
if (! Float.isNaN(currentDeg)) {
float degPerNick = 360.0f / totalNicks;
float deltaDeg = dragStartDeg - currentDeg;
final int nicks = (int) (Math.signum(deltaDeg)
* Math.floor(Math.abs(deltaDeg) / degPerNick));
if (nicks != 0) {
dragStartDeg = currentDeg;
rotate(nicks);
}
}
return true;
} else {
return false;
}
}
#Override
public void onShowPress(MotionEvent e) {
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
}
I want 0-9 according to user selection & also allow user rotation to 0-9 not more rotation.
I have also check another code this is below.
dialer = (ImageView) findViewById(R.id.imageView_ring);
dialer.setOnTouchListener(new MyOnTouchListener());
dialer.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// method called more than once, but the values only need to be initialized one time
if (dialerHeight == 0 || dialerWidth == 0) {
dialerHeight = dialer.getHeight();
dialerWidth = dialer.getWidth();
// resize
Matrix resize = new Matrix();
resize.postScale((float)Math.min(dialerWidth, dialerHeight) / (float)imageOriginal.getWidth(), (float)Math.min(dialerWidth, dialerHeight) / (float)imageOriginal.getHeight());
imageScaled = Bitmap.createBitmap(imageOriginal, 0, 0, imageOriginal.getWidth(), imageOriginal.getHeight(), resize, false);
// translate to the image view's center
float translateX = dialerWidth / 2 - imageScaled.getWidth() / 2;
float translateY = dialerHeight / 2 - imageScaled.getHeight() / 2;
matrix.postTranslate(translateX, translateY);
dialer.setImageBitmap(imageScaled);
dialer.setImageMatrix(matrix);
Log.e("Rotation degree :"+rotationDegrees, String.valueOf(tickNumber));
}
}
});
int tickNumber = 0;
private void rotateDialer(float degrees) {
//System.out.println("Rotation Done :: "+rotationDone);
// if(!rotationDone) {
this.rotationDegrees += degrees;
this.rotationDegrees = this.rotationDegrees % 360;
tickNumber = (int)this.rotationDegrees*100/360;
// It could be negative
if (tickNumber > 0) tickNumber = 100 - tickNumber;
//this.rotationDegrees = Math.abs(rotationDegrees);
this.tickNumber = Math.abs(tickNumber);
if(tickNumber < 20 || tickNumber > 80){
Log.e("Rotation degree :"+rotationDegrees, String.valueOf(tickNumber));
matrix.postRotate(degrees, dialerWidth / 2, dialerHeight / 2);
dialer.setImageMatrix(matrix);
}
// }
}
/**
* #return The angle of the unit circle with the image view's center
*/
private double getAngle(double xTouch, double yTouch) {
double delta_x = xTouch - (dialerWidth) /2;
double delta_y = (dialerHeight) /2 - yTouch;
double radians = Math.atan2(delta_y, delta_x);
double dx = xTouch - dWidth;
double dy = (dHeight - ((dialerHeight) /2)) - yTouch;
double dRadi = Math.atan2(dy, dx);
//Log.e("MY degree", String.valueOf( Math.toDegrees(dRadi)));
//return Math.toDegrees(dRadi);
return Math.toDegrees(radians);
}
/**
* Simple implementation of an {#link OnTouchListener} for registering the dialer's touch events.
*/
private class MyOnTouchListener implements OnTouchListener {
private double startAngle;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// reset the touched quadrants
/*for (int i = 0; i < quadrantTouched.length; i++) {
quadrantTouched[i] = false;
}*/
//allowRotating = false;
startAngle = getAngle(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
/*double rotationAngleRadians = Math.atan2(event.getX() - (dialer.getWidth() / 2 ), ( (dialer.getHeight() / 2 ) - event.getY()));
double angle = (int) Math.toDegrees(rotationAngleRadians);
Log.i("gg", "rotaion angle"+angle);*/
double currentAngle = getAngle(event.getX(), event.getY());
//if(currentAngle < 130 || currentAngle < 110){
//Log.e("Start angle :"+startAngle, "Current angle:"+currentAngle);
rotateDialer((float) (startAngle - currentAngle));
startAngle = currentAngle;
//}
//Log.e("MOVE start Degree:"+startAngle, "Current Degree :"+currentAngle);
break;
case MotionEvent.ACTION_UP:
//allowRotating = true;
break;
}
// set the touched quadrant to true
//quadrantTouched[getQuadrant(event.getX() - (dialerWidth / 2), dialerHeight - event.getY() - (dialerHeight / 2))] = true;
//detector.onTouchEvent(event);
return true;
}
}
I do not understand your problem. The code below rotate the image 48 degrees.
ImageView dialer = (ImageView) findViewById(R.id.imageView_ring);
int degrees = 48;
Matrix matrix = new Matrix();
matrix.setRotate(degrees);
Bitmap bmpBowRotated = Bitmap.createBitmap(imageOrginal, 0, 0, imageOrginal.getWidth(),imageOrginal.getHeight(), matrix, false);
dialer.setImageBitmap(bmpBowRotated);
Hi Girish there is a class Named RotateAnimation by using this class u can easily do it
look Example like
RotateAnimation r = new RotateAnimation(0f, -90f,200,200); // HERE
r.setStartOffset(1000);
r.setDuration(1000);
r.setFillAfter(true); //HERE
animationSet.addAnimation(r);
I would like to first know what will be there for deployment? Does it allow manipulation Evenets? if yes then you get handle ManipulationStatring and ManipulationDelta Event to rotate the element.
If the same is not the case where Manipulation is not available then you can try RenderTransformation property with RorateTransform of the element is you are working with WPf.
I was able to achieve this by doing few of the following tweaks on your code
Making user click exactly on the arrow always to get the initial angle at which the arrow is placed, in your case 90 degree, else return false
Also save the angle at which the user removed his finger and use that angle as the initial value for his next touch ,like if he placed arrow at 100 deg make that his initial touch position to activate rotation again
Now for checking his answer take the angle at which your numbers 0 to 9 are placed ,im guessing your values take 120 deg from 0 to 9, divide that angle by 10, you can easily find out what angle represents what value and get your result
Also touching exactly at 90deg to begin rotation is very irritating, so always check for value which is bw 90+4 and 90-4 to begin, but always use the 90 as your start angle

Android ImageView Zoom-in and Zoom-Out

I want to Zoom-in and Zoom-out an Android ImageView. I tried most of the samples but in all of them the image in the ImageView itself is getting Zoomed-in and Zoomed-out, while I want to Zoom-in and Zoom-out the ImageView. I want to increase the ImageView width and height while Zooming-in and reduce the ImageView width and height while Zooming-out. How do I achieve that?
Please follow the below class, that is used for Zoom in and Zoom Out for ImageView.
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class ZoomInZoomOut extends Activity implements OnTouchListener
{
private static final String TAG = "Touch";
#SuppressWarnings("unused")
private static final float MIN_ZOOM = 1f,MAX_ZOOM = 1f;
// These matrices will be used to scale points of the image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
// The 3 states (events) which the user is trying to perform
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// these PointF objects are used to record the point(s) the user is touching
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView view = (ImageView) findViewById(R.id.imageView);
view.setOnTouchListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
ImageView view = (ImageView) v;
view.setScaleType(ImageView.ScaleType.MATRIX);
float scale;
dumpEvent(event);
// Handle touch events here...
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN: // first finger down only
matrix.set(view.getImageMatrix());
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG, "mode=DRAG"); // write to LogCat
mode = DRAG;
break;
case MotionEvent.ACTION_UP: // first finger lifted
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
mode = NONE;
Log.d(TAG, "mode=NONE");
break;
case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 5f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG)
{
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); // create the transformation in the matrix of points
}
else if (mode == ZOOM)
{
// 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);
}
}
break;
}
view.setImageMatrix(matrix); // display the transformation on screen
return true; // indicate event was handled
}
/*
* --------------------------------------------------------------------------
* Method: spacing Parameters: MotionEvent Returns: float Description:
* checks the spacing between the two fingers on touch
* ----------------------------------------------------
*/
private float spacing(MotionEvent event)
{
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
/*
* --------------------------------------------------------------------------
* Method: midPoint Parameters: PointF object, MotionEvent Returns: void
* Description: calculates the midpoint between the 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);
}
/** Show an event in the LogCat view, for debugging */
private void dumpEvent(MotionEvent event)
{
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE","POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP)
{
sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++)
{
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";");
}
sb.append("]");
Log.d("Touch Events ---------", sb.toString());
}
}
The other implementations here all have some kind of a flaw. so i basically mixed them up and came up with this.
Create a custom view like this:
ZoomableImageView.java:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class ZoomableImageView extends ImageView
{
Matrix matrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
static final int CLICK = 3;
int mode = NONE;
PointF last = new PointF();
PointF start = new PointF();
float minScale = 1f;
float maxScale = 4f;
float[] m;
float redundantXSpace, redundantYSpace;
float width, height;
float saveScale = 1f;
float right, bottom, origWidth, origHeight, bmWidth, bmHeight;
ScaleGestureDetector mScaleDetector;
Context context;
public ZoomableImageView(Context context, AttributeSet attr)
{
super(context, attr);
super.setClickable(true);
this.context = context;
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
matrix.setTranslate(1f, 1f);
m = new float[9];
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
mScaleDetector.onTouchEvent(event);
matrix.getValues(m);
float x = m[Matrix.MTRANS_X];
float y = m[Matrix.MTRANS_Y];
PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction())
{
//when one finger is touching
//set the mode to DRAG
case MotionEvent.ACTION_DOWN:
last.set(event.getX(), event.getY());
start.set(last);
mode = DRAG;
break;
//when two fingers are touching
//set the mode to ZOOM
case MotionEvent.ACTION_POINTER_DOWN:
last.set(event.getX(), event.getY());
start.set(last);
mode = ZOOM;
break;
//when a finger moves
//If mode is applicable move image
case MotionEvent.ACTION_MOVE:
//if the mode is ZOOM or
//if the mode is DRAG and already zoomed
if (mode == ZOOM || (mode == DRAG && saveScale > minScale))
{
float deltaX = curr.x - last.x;// x difference
float deltaY = curr.y - last.y;// y difference
float scaleWidth = Math.round(origWidth * saveScale);// width after applying current scale
float scaleHeight = Math.round(origHeight * saveScale);// height after applying current scale
//if scaleWidth is smaller than the views width
//in other words if the image width fits in the view
//limit left and right movement
if (scaleWidth < width)
{
deltaX = 0;
if (y + deltaY > 0)
deltaY = -y;
else if (y + deltaY < -bottom)
deltaY = -(y + bottom);
}
//if scaleHeight is smaller than the views height
//in other words if the image height fits in the view
//limit up and down movement
else if (scaleHeight < height)
{
deltaY = 0;
if (x + deltaX > 0)
deltaX = -x;
else if (x + deltaX < -right)
deltaX = -(x + right);
}
//if the image doesnt fit in the width or height
//limit both up and down and left and right
else
{
if (x + deltaX > 0)
deltaX = -x;
else if (x + deltaX < -right)
deltaX = -(x + right);
if (y + deltaY > 0)
deltaY = -y;
else if (y + deltaY < -bottom)
deltaY = -(y + bottom);
}
//move the image with the matrix
matrix.postTranslate(deltaX, deltaY);
//set the last touch location to the current
last.set(curr.x, curr.y);
}
break;
//first finger is lifted
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(curr.x - start.x);
int yDiff = (int) Math.abs(curr.y - start.y);
if (xDiff < CLICK && yDiff < CLICK)
performClick();
break;
// second finger is lifted
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(matrix);
invalidate();
return true;
}
});
}
#Override
public void setImageBitmap(Bitmap bm)
{
super.setImageBitmap(bm);
bmWidth = bm.getWidth();
bmHeight = bm.getHeight();
}
public void setMaxZoom(float x)
{
maxScale = x;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
#Override
public boolean onScaleBegin(ScaleGestureDetector detector)
{
mode = ZOOM;
return true;
}
#Override
public boolean onScale(ScaleGestureDetector detector)
{
float mScaleFactor = detector.getScaleFactor();
float origScale = saveScale;
saveScale *= mScaleFactor;
if (saveScale > maxScale)
{
saveScale = maxScale;
mScaleFactor = maxScale / origScale;
}
else if (saveScale < minScale)
{
saveScale = minScale;
mScaleFactor = minScale / origScale;
}
right = width * saveScale - width - (2 * redundantXSpace * saveScale);
bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
if (origWidth * saveScale <= width || origHeight * saveScale <= height)
{
matrix.postScale(mScaleFactor, mScaleFactor, width / 2, height / 2);
if (mScaleFactor < 1)
{
matrix.getValues(m);
float x = m[Matrix.MTRANS_X];
float y = m[Matrix.MTRANS_Y];
if (mScaleFactor < 1)
{
if (Math.round(origWidth * saveScale) < width)
{
if (y < -bottom)
matrix.postTranslate(0, -(y + bottom));
else if (y > 0)
matrix.postTranslate(0, -y);
}
else
{
if (x < -right)
matrix.postTranslate(-(x + right), 0);
else if (x > 0)
matrix.postTranslate(-x, 0);
}
}
}
}
else
{
matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());
matrix.getValues(m);
float x = m[Matrix.MTRANS_X];
float y = m[Matrix.MTRANS_Y];
if (mScaleFactor < 1) {
if (x < -right)
matrix.postTranslate(-(x + right), 0);
else if (x > 0)
matrix.postTranslate(-x, 0);
if (y < -bottom)
matrix.postTranslate(0, -(y + bottom));
else if (y > 0)
matrix.postTranslate(0, -y);
}
}
return true;
}
}
#Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
//Fit to screen.
float scale;
float scaleX = width / bmWidth;
float scaleY = height / bmHeight;
scale = Math.min(scaleX, scaleY);
matrix.setScale(scale, scale);
setImageMatrix(matrix);
saveScale = 1f;
// Center the image
redundantYSpace = height - (scale * bmHeight) ;
redundantXSpace = width - (scale * bmWidth);
redundantYSpace /= 2;
redundantXSpace /= 2;
matrix.postTranslate(redundantXSpace, redundantYSpace);
origWidth = width - 2 * redundantXSpace;
origHeight = height - 2 * redundantYSpace;
right = width * saveScale - width - (2 * redundantXSpace * saveScale);
bottom = height * saveScale - height - (2 * redundantYSpace * saveScale);
setImageMatrix(matrix);
}
}
Then add the image like this:
ZoomableImageView touch = (ZoomableImageView)findViewById(R.id.IMAGEID);
touch.setImageBitmap(bitmap);
Add the view like this in XML:
<PACKAGE.ZoomableImageView
android:id="#+id/IMAGEID"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Simple way:
PhotoViewAttacher pAttacher;
pAttacher = new PhotoViewAttacher(Your_Image_View);
pAttacher.update();
Add below line in build.gradle:
compile 'com.commit451:PhotoView:1.2.4'
Make two java classes
Zoom class
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class Zoom extends View {
private Drawable image;
ImageButton img,img1;
private int zoomControler=20;
public Zoom(Context context){
super(context);
image=context.getResources().getDrawable(R.drawable.j);
//image=context.getResources().getDrawable(R.drawable.icon);
setFocusable(true);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//here u can control the width and height of the images........ this line is very important
image.setBounds((getWidth()/2)-zoomControler, (getHeight()/2)-zoomControler, (getWidth()/2)+zoomControler, (getHeight()/2)+zoomControler);
image.draw(canvas);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_DPAD_UP){
// zoom in
zoomControler+=10;
}
if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){
// zoom out
zoomControler-=10;
}
if(zoomControler<10){
zoomControler=10;
}
invalidate();
return true;
}
}
make second class
import android.app.Activity;
import android.os.Bundle;
public class Zoomexample extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(new Zoom(this));
}
}
I have improved the answer I got from stack for flawless ZOOM (two finger) / ROTATION (two finger) / DRAG (Single finger).
//============================XML code==================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.flochat.imageviewzoomforstack.MainActivity">
<ImageView
android:id="#+id/imageview_trash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/trash" />
</LinearLayout>
//============================Java code==========================
public class MainActivity extends AppCompatActivity {
ImageView photoview2;
float[] lastEvent = null;
float d = 0f;
float newRot = 0f;
private boolean isZoomAndRotate;
private boolean isOutSide;
private static final int NONE = 0;
private static final int DRAG = 1;
private static final int ZOOM = 2;
private int mode = NONE;
private PointF start = new PointF();
private PointF mid = new PointF();
float oldDist = 1f;
private float xCoOrdinate, yCoOrdinate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
photoview2 = findViewById(R.id.imageview_trash);
photoview2.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
view.bringToFront();
viewTransformation(view, event);
return true;
}
});
}
private void viewTransformation(View view, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
xCoOrdinate = view.getX() - event.getRawX();
yCoOrdinate = view.getY() - event.getRawY();
start.set(event.getX(), event.getY());
isOutSide = false;
mode = DRAG;
lastEvent = null;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f) {
midPoint(mid, event);
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;
case MotionEvent.ACTION_UP:
isZoomAndRotate = false;
if (mode == DRAG) {
float x = event.getX();
float y = event.getY();
}
case MotionEvent.ACTION_OUTSIDE:
isOutSide = true;
mode = NONE;
lastEvent = null;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
lastEvent = null;
break;
case MotionEvent.ACTION_MOVE:
if (!isOutSide) {
if (mode == DRAG) {
isZoomAndRotate = false;
view.animate().x(event.getRawX() + xCoOrdinate).y(event.getRawY() + yCoOrdinate).setDuration(0).start();
}
if (mode == ZOOM && event.getPointerCount() == 2) {
float newDist1 = spacing(event);
if (newDist1 > 10f) {
float scale = newDist1 / oldDist * view.getScaleX();
view.setScaleX(scale);
view.setScaleY(scale);
}
if (lastEvent != null) {
newRot = rotation(event);
view.setRotation((float) (view.getRotation() + (newRot - d)));
}
}
}
break;
}
}
private float rotation(MotionEvent event) {
double delta_x = (event.getX(0) - event.getX(1));
double delta_y = (event.getY(0) - event.getY(1));
double radians = Math.atan2(delta_y, delta_x);
return (float) Math.toDegrees(radians);
}
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (int) Math.sqrt(x * x + y * y);
}
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);
}
}
//========================Just pass any view which you want to zoom/rotate/drag to viewTransformation() method. Very applicable for textview zoom. It will not pixelate text.
It's old, but this may help someone else.
Below TouchImageView class supports both zooming in/out on either pinch or double tap
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class TouchImageView extends ImageView implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
Matrix matrix;
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF last = new PointF();
PointF start = new PointF();
float minScale = 1f;
float maxScale = 3f;
float[] m;
int viewWidth, viewHeight;
static final int CLICK = 3;
float saveScale = 1f;
protected float origWidth, origHeight;
int oldMeasuredWidth, oldMeasuredHeight;
ScaleGestureDetector mScaleDetector;
Context context;
public TouchImageView(Context context) {
super(context);
sharedConstructing(context);
}
public TouchImageView(Context context, AttributeSet attrs) {
super(context, attrs);
sharedConstructing(context);
}
GestureDetector mGestureDetector;
private void sharedConstructing(Context context) {
super.setClickable(true);
this.context = context;
mGestureDetector = new GestureDetector(context, this);
mGestureDetector.setOnDoubleTapListener(this);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
matrix = new Matrix();
m = new float[9];
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mGestureDetector.onTouchEvent(event);
PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
last.set(curr);
start.set(last);
mode = DRAG;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
float deltaX = curr.x - last.x;
float deltaY = curr.y - last.y;
float fixTransX = getFixDragTrans(deltaX, viewWidth,
origWidth * saveScale);
float fixTransY = getFixDragTrans(deltaY, viewHeight,
origHeight * saveScale);
matrix.postTranslate(fixTransX, fixTransY);
fixTrans();
last.set(curr.x, curr.y);
}
break;
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(curr.x - start.x);
int yDiff = (int) Math.abs(curr.y - start.y);
if (xDiff < CLICK && yDiff < CLICK)
performClick();
break;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(matrix);
invalidate();
return true; // indicate event was handled
}
});
}
public void setMaxZoom(float x) {
maxScale = x;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
// Double tap is detected
Log.i("MAIN_TAG", "Double tap detected");
float origScale = saveScale;
float mScaleFactor;
if (saveScale == maxScale) {
saveScale = minScale;
mScaleFactor = minScale / origScale;
} else {
saveScale = maxScale;
mScaleFactor = maxScale / origScale;
}
matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
viewHeight / 2);
fixTrans();
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
#Override
public boolean onDown(MotionEvent e) {
return false;
}
#Override
public void onShowPress(MotionEvent e) {
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
#Override
public void onLongPress(MotionEvent e) {
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
#Override
public boolean onScale(ScaleGestureDetector detector) {
float mScaleFactor = detector.getScaleFactor();
float origScale = saveScale;
saveScale *= mScaleFactor;
if (saveScale > maxScale) {
saveScale = maxScale;
mScaleFactor = maxScale / origScale;
} else if (saveScale < minScale) {
saveScale = minScale;
mScaleFactor = minScale / origScale;
}
if (origWidth * saveScale <= viewWidth
|| origHeight * saveScale <= viewHeight)
matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
viewHeight / 2);
else
matrix.postScale(mScaleFactor, mScaleFactor,
detector.getFocusX(), detector.getFocusY());
fixTrans();
return true;
}
}
void fixTrans() {
matrix.getValues(m);
float transX = m[Matrix.MTRANS_X];
float transY = m[Matrix.MTRANS_Y];
float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
float fixTransY = getFixTrans(transY, viewHeight, origHeight
* saveScale);
if (fixTransX != 0 || fixTransY != 0)
matrix.postTranslate(fixTransX, fixTransY);
}
float getFixTrans(float trans, float viewSize, float contentSize) {
float minTrans, maxTrans;
if (contentSize <= viewSize) {
minTrans = 0;
maxTrans = viewSize - contentSize;
} else {
minTrans = viewSize - contentSize;
maxTrans = 0;
}
if (trans < minTrans)
return -trans + minTrans;
if (trans > maxTrans)
return -trans + maxTrans;
return 0;
}
float getFixDragTrans(float delta, float viewSize, float contentSize) {
if (contentSize <= viewSize) {
return 0;
}
return delta;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
viewWidth = MeasureSpec.getSize(widthMeasureSpec);
viewHeight = MeasureSpec.getSize(heightMeasureSpec);
//
// Rescales image on rotation
//
if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight
|| viewWidth == 0 || viewHeight == 0)
return;
oldMeasuredHeight = viewHeight;
oldMeasuredWidth = viewWidth;
if (saveScale == 1) {
// Fit to screen.
float scale;
Drawable drawable = getDrawable();
if (drawable == null || drawable.getIntrinsicWidth() == 0
|| drawable.getIntrinsicHeight() == 0)
return;
int bmWidth = drawable.getIntrinsicWidth();
int bmHeight = drawable.getIntrinsicHeight();
Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight);
float scaleX = (float) viewWidth / (float) bmWidth;
float scaleY = (float) viewHeight / (float) bmHeight;
scale = Math.min(scaleX, scaleY);
matrix.setScale(scale, scale);
// Center the image
float redundantYSpace = (float) viewHeight
- (scale * (float) bmHeight);
float redundantXSpace = (float) viewWidth
- (scale * (float) bmWidth);
redundantYSpace /= (float) 2;
redundantXSpace /= (float) 2;
matrix.postTranslate(redundantXSpace, redundantYSpace);
origWidth = viewWidth - 2 * redundantXSpace;
origHeight = viewHeight - 2 * redundantYSpace;
setImageMatrix(matrix);
}
fixTrans();
}
}
Usage:
You can replace your ImageView with TouchImageView in both XML & java
1. For XML
<?xml version="1.0" encoding="utf-8"?>
<com.example.android.myapp.TouchImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/imViewedImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true" />
2. For Java
TouchImageView imViewedImage = findViewById(R.id.imViewedImage);
This is yet another implementation based on the code posted by Nicolas Tyler.
The following bugs are fixed:
Setting minScale to a number less than 1 now works
You don't need to use setImageBitmap() to set the image (you can use, for example setImageResource()
All constructors now work properly
The following things, amongst others are tidied up:
An OnTouchListener is not used, it's not necessary because the the class can just implement the onTouchEvent() method.
The assignment right = width * saveScale - width - (2 * redundantXSpace * saveScale); has been simplified to right = (originalBitmapWidth * saveScale) - width Which, in my option, is much less confusing.
Some member variables are removed (more state can probably be removed from this class)
It's not perfect but here you go:
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;
/**
* Created by alex on 23/02/16.
* Based on code posted by Nicolas Tyler here:
* https://stackoverflow.com/questions/6650398/android-imageview-zoom-in-and-zoom-out
*/
public class ZoomableImageView extends ImageView {
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
#Override
public boolean onScale(ScaleGestureDetector detector) {
float scaleFactor = detector.getScaleFactor();
float newScale = saveScale * scaleFactor;
if (newScale < maxScale && newScale > minScale) {
saveScale = newScale;
float width = getWidth();
float height = getHeight();
right = (originalBitmapWidth * saveScale) - width;
bottom = (originalBitmapHeight * saveScale) - height;
float scaledBitmapWidth = originalBitmapWidth * saveScale;
float scaledBitmapHeight = originalBitmapHeight * saveScale;
if (scaledBitmapWidth <= width || scaledBitmapHeight <= height) {
matrix.postScale(scaleFactor, scaleFactor, width / 2, height / 2);
} else {
matrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
}
}
return true;
}
}
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
static final int CLICK = 3;
private int mode = NONE;
private Matrix matrix = new Matrix();
private PointF last = new PointF();
private PointF start = new PointF();
private float minScale = 0.5f;
private float maxScale = 4f;
private float[] m;
private float redundantXSpace, redundantYSpace;
private float saveScale = 1f;
private float right, bottom, originalBitmapWidth, originalBitmapHeight;
private ScaleGestureDetector mScaleDetector;
public ZoomableImageView(Context context) {
super(context);
init(context);
}
public ZoomableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ZoomableImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
super.setClickable(true);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
m = new float[9];
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int bmHeight = getBmHeight();
int bmWidth = getBmWidth();
float width = getMeasuredWidth();
float height = getMeasuredHeight();
//Fit to screen.
float scale = width > height ? height / bmHeight : width / bmWidth;
matrix.setScale(scale, scale);
saveScale = 1f;
originalBitmapWidth = scale * bmWidth;
originalBitmapHeight = scale * bmHeight;
// Center the image
redundantYSpace = (height - originalBitmapHeight);
redundantXSpace = (width - originalBitmapWidth);
matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
setImageMatrix(matrix);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
matrix.getValues(m);
float x = m[Matrix.MTRANS_X];
float y = m[Matrix.MTRANS_Y];
PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
//when one finger is touching
//set the mode to DRAG
case MotionEvent.ACTION_DOWN:
last.set(event.getX(), event.getY());
start.set(last);
mode = DRAG;
break;
//when two fingers are touching
//set the mode to ZOOM
case MotionEvent.ACTION_POINTER_DOWN:
last.set(event.getX(), event.getY());
start.set(last);
mode = ZOOM;
break;
//when a finger moves
//If mode is applicable move image
case MotionEvent.ACTION_MOVE:
//if the mode is ZOOM or
//if the mode is DRAG and already zoomed
if (mode == ZOOM || (mode == DRAG && saveScale > minScale)) {
float deltaX = curr.x - last.x;// x difference
float deltaY = curr.y - last.y;// y difference
float scaleWidth = Math.round(originalBitmapWidth * saveScale);// width after applying current scale
float scaleHeight = Math.round(originalBitmapHeight * saveScale);// height after applying current scale
boolean limitX = false;
boolean limitY = false;
//if scaleWidth is smaller than the views width
//in other words if the image width fits in the view
//limit left and right movement
if (scaleWidth < getWidth() && scaleHeight < getHeight()) {
// don't do anything
}
else if (scaleWidth < getWidth()) {
deltaX = 0;
limitY = true;
}
//if scaleHeight is smaller than the views height
//in other words if the image height fits in the view
//limit up and down movement
else if (scaleHeight < getHeight()) {
deltaY = 0;
limitX = true;
}
//if the image doesnt fit in the width or height
//limit both up and down and left and right
else {
limitX = true;
limitY = true;
}
if (limitY) {
if (y + deltaY > 0) {
deltaY = -y;
} else if (y + deltaY < -bottom) {
deltaY = -(y + bottom);
}
}
if (limitX) {
if (x + deltaX > 0) {
deltaX = -x;
} else if (x + deltaX < -right) {
deltaX = -(x + right);
}
}
//move the image with the matrix
matrix.postTranslate(deltaX, deltaY);
//set the last touch location to the current
last.set(curr.x, curr.y);
}
break;
//first finger is lifted
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(curr.x - start.x);
int yDiff = (int) Math.abs(curr.y - start.y);
if (xDiff < CLICK && yDiff < CLICK)
performClick();
break;
// second finger is lifted
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(matrix);
invalidate();
return true;
}
public void setMaxZoom(float x) {
maxScale = x;
}
private int getBmWidth() {
Drawable drawable = getDrawable();
if (drawable != null) {
return drawable.getIntrinsicWidth();
}
return 0;
}
private int getBmHeight() {
Drawable drawable = getDrawable();
if (drawable != null) {
return drawable.getIntrinsicHeight();
}
return 0;
}
}
just use this class : TouchImageView
I made my own custom imageview with pinch to zoom. There is no limits/borders on Chirag Ravals code, so user can drag the image off the screen.
Here is the CustomImageView class:
public class CustomImageVIew extends ImageView implements OnTouchListener {
private Matrix matrix = new Matrix();
private Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
private int mode = NONE;
private PointF mStartPoint = new PointF();
private PointF mMiddlePoint = new PointF();
private Point mBitmapMiddlePoint = new Point();
private float oldDist = 1f;
private float matrixValues[] = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f};
private float scale;
private float oldEventX = 0;
private float oldEventY = 0;
private float oldStartPointX = 0;
private float oldStartPointY = 0;
private int mViewWidth = -1;
private int mViewHeight = -1;
private int mBitmapWidth = -1;
private int mBitmapHeight = -1;
private boolean mDraggable = false;
public CustomImageVIew(Context context) {
this(context, null, 0);
}
public CustomImageVIew(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomImageVIew(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setOnTouchListener(this);
}
#Override
public void onSizeChanged (int w, int h, int oldw, int oldh){
super.onSizeChanged(w, h, oldw, oldh);
mViewWidth = w;
mViewHeight = h;
}
public void setBitmap(Bitmap bitmap){
if(bitmap != null){
setImageBitmap(bitmap);
mBitmapWidth = bitmap.getWidth();
mBitmapHeight = bitmap.getHeight();
mBitmapMiddlePoint.x = (mViewWidth / 2) - (mBitmapWidth / 2);
mBitmapMiddlePoint.y = (mViewHeight / 2) - (mBitmapHeight / 2);
matrix.postTranslate(mBitmapMiddlePoint.x, mBitmapMiddlePoint.y);
this.setImageMatrix(matrix);
}
}
#Override
public boolean onTouch(View v, MotionEvent event){
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
mStartPoint.set(event.getX(), event.getY());
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if(oldDist > 10f){
savedMatrix.set(matrix);
midPoint(mMiddlePoint, event);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if(mode == DRAG){
drag(event);
} else if(mode == ZOOM){
zoom(event);
}
break;
}
return true;
}
public void drag(MotionEvent event){
matrix.getValues(matrixValues);
float left = matrixValues[2];
float top = matrixValues[5];
float bottom = (top + (matrixValues[0] * mBitmapHeight)) - mViewHeight;
float right = (left + (matrixValues[0] * mBitmapWidth)) -mViewWidth;
float eventX = event.getX();
float eventY = event.getY();
float spacingX = eventX - mStartPoint.x;
float spacingY = eventY - mStartPoint.y;
float newPositionLeft = (left < 0 ? spacingX : spacingX * -1) + left;
float newPositionRight = (spacingX) + right;
float newPositionTop = (top < 0 ? spacingY : spacingY * -1) + top;
float newPositionBottom = (spacingY) + bottom;
boolean x = true;
boolean y = true;
if(newPositionRight < 0.0f || newPositionLeft > 0.0f){
if(newPositionRight < 0.0f && newPositionLeft > 0.0f){
x = false;
} else{
eventX = oldEventX;
mStartPoint.x = oldStartPointX;
}
}
if(newPositionBottom < 0.0f || newPositionTop > 0.0f){
if(newPositionBottom < 0.0f && newPositionTop > 0.0f){
y = false;
} else{
eventY = oldEventY;
mStartPoint.y = oldStartPointY;
}
}
if(mDraggable){
matrix.set(savedMatrix);
matrix.postTranslate(x? eventX - mStartPoint.x : 0, y? eventY - mStartPoint.y : 0);
this.setImageMatrix(matrix);
if(x)oldEventX = eventX;
if(y)oldEventY = eventY;
if(x)oldStartPointX = mStartPoint.x;
if(y)oldStartPointY = mStartPoint.y;
}
}
public void zoom(MotionEvent event){
matrix.getValues(matrixValues);
float newDist = spacing(event);
float bitmapWidth = matrixValues[0] * mBitmapWidth;
float bimtapHeight = matrixValues[0] * mBitmapHeight;
boolean in = newDist > oldDist;
if(!in && matrixValues[0] < 1){
return;
}
if(bitmapWidth > mViewWidth || bimtapHeight > mViewHeight){
mDraggable = true;
} else{
mDraggable = false;
}
float midX = (mViewWidth / 2);
float midY = (mViewHeight / 2);
matrix.set(savedMatrix);
scale = newDist / oldDist;
matrix.postScale(scale, scale, bitmapWidth > mViewWidth ? mMiddlePoint.x : midX, bimtapHeight > mViewHeight ? mMiddlePoint.y : midY);
this.setImageMatrix(matrix);
}
/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float)Math.sqrt(x * x + y * y);
}
/** 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);
}
}
This is how you can use it in your activity:
CustomImageVIew mImageView = (CustomImageVIew)findViewById(R.id.customImageVIew1);
mImage.setBitmap(your bitmap);
And layout:
<your.package.name.CustomImageVIew
android:id="#+id/customImageVIew1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:scaleType="matrix"/> // important
I think Chirag Ravals' answer is great!
The only thing it could be improved is moving all this code inside some class like:
PinchZoomImageView extends ImageView {...
and adding there initial Image Matrix initialization to prevent zooming after the first tap:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
matrix = new Matrix(this.getImageMatrix());
}
BTW, this will fix a bug mentioned by Muhammad Umar and Baz
P.S. Having Max and Min zoom limits could be also useful.
E.g Max zoom is 2X and min zoom is the original scale when the image is fitted to screen:
static final int MAX_SCALE_FACTOR = 2;
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Getting initial Image matrix
mViewMatrix = new Matrix(this.getImageMatrix());
mMinScaleMatrix = new Matrix(mViewMatrix);
float initialScale = getMatrixScale(mViewMatrix);
if (initialScale < 1.0f) // Image is bigger than screen
mMaxScale = MAX_SCALE_FACTOR;
else
mMaxScale = MAX_SCALE_FACTOR * initialScale;
mMinScale = getMatrixScale(mMinScaleMatrix);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
// We set scale only after onMeasure was called and automatically fit image to screen
if(!mWasScaleTypeSet) {
view.setScaleType(ImageView.ScaleType.MATRIX);
mWasScaleTypeSet = true;
}
float scale;
dumpEvent(event);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
mCurSavedMatrix.set(mViewMatrix);
start.set(event.getX(), event.getY());
mCurrentMode = DRAG;
break;
case MotionEvent.ACTION_UP: // first finger lifted
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
mCurrentMode = NONE;
float resScale = getMatrixScale(mViewMatrix);
if (resScale > mMaxScale) {
downscaleMatrix(resScale, mViewMatrix);
} else if (resScale < mMinScale)
mViewMatrix = new Matrix(mMinScaleMatrix);
else if ((resScale - mMinScale) < 0.1f) // Don't allow user to drag picture outside in case of FIT TO WINDOW zoom
mViewMatrix = new Matrix(mMinScaleMatrix);
else
break;
break;
case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down
mOldDist = spacing(event);
Helper.LOGD(TAG, "oldDist=" + mOldDist);
if (mOldDist > 5f) {
mCurSavedMatrix.set(mViewMatrix);
midPoint(mCurMidPoint, event);
mCurrentMode = ZOOM;
Helper.LOGD(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_MOVE:
if (mCurrentMode == DRAG) {
mViewMatrix.set(mCurSavedMatrix);
mViewMatrix.postTranslate(event.getX() - start.x, event.getY() - start.y); // create the transformation in the matrix of points
} else if (mCurrentMode == ZOOM) {
// pinch zooming
float newDist = spacing(event);
Helper.LOGD(TAG, "newDist=" + newDist);
if (newDist > 1.f) {
mViewMatrix.set(mCurSavedMatrix);
scale = newDist / mOldDist; // setting the scaling of the
// matrix...if scale > 1 means
// zoom in...if scale < 1 means
// zoom out
mViewMatrix.postScale(scale, scale, mCurMidPoint.x, mCurMidPoint.y);
}
}
break;
}
view.setImageMatrix(mViewMatrix); // display the transformation on screen
return true; // indicate event was handled
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////// PRIVATE SECTION ///////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// These matrices will be used to scale points of the image
private Matrix mViewMatrix = new Matrix();
private Matrix mCurSavedMatrix = new Matrix();
// These PointF objects are used to record the point(s) the user is touching
private PointF start = new PointF();
private PointF mCurMidPoint = new PointF();
private float mOldDist = 1f;
private Matrix mMinScaleMatrix;
private float mMinScale;
private float mMaxScale;
float[] mTmpValues = new float[9];
private boolean mWasScaleTypeSet;
/**
* Returns scale factor of the Matrix
* #param matrix
* #return
*/
private float getMatrixScale(Matrix matrix) {
matrix.getValues(mTmpValues);
return mTmpValues[Matrix.MSCALE_X];
}
/**
* Downscales matrix with the scale to maximum allowed scale factor, but the same translations
* #param scale
* #param dist
*/
private void downscaleMatrix(float scale, Matrix dist) {
float resScale = mMaxScale / scale;
dist.postScale(resScale, resScale, mCurMidPoint.x, mCurMidPoint.y);
}
I got the most helpful answer from #Nicolas Tyler but I had issues with how the syntax and logic worked. I also did not want any Alpha space and my Algebra was rusty! After 3 days I have put together my own version of this.
My answer differs from #Nicolas Tyler with the following:
Different variable names which I found made more sense in underlying contextual uses
This Pinch-Zoom image class does NOT show alpha space and will let you zoom in and out and still not let you over/under pan an image and reveal alpha space
Added deep comments to the matrix section to explain what was going on with the math involved
This image class will also let you pass in a resourceId and it will create a bitmap from it
Much simpler algorithms for both scaling and translation and few variables
Changing the image within this will cause it to zoom in/out such that the new image takes up the view container
A great resource refresher on Algebra can be found here:
https://youtu.be/IiXB6tYtY4w?t=4m12s
That video covers the core of Scalar and Translation matrixes (and will help you make sense of the MTRANS_X and MTRANS_Y stuff). If you have questions ask and I will do my best to answer (but I am NO Algebra expert).
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class iImage extends ImageView
{
static final int NONE_MODE = 0;
static final int DRAG_MODE = 1;
static final int ZOOM_MODE = 2;
int _mode = NONE_MODE;
Matrix _matrix = new Matrix();
PointF _previousPoint = new PointF();
PointF _startPoint = new PointF();
float _currentScale = 1f;
float _minScale = 1f;
float _maxScale = 3f;
float[] _arrayOf9Floats;
float _bitmapWidth, _bitmapHeight,_displayWidth, _displayHeight;
ScaleGestureDetector _scaleDetector;
Context _context;
public iImage(Context context)
{
super(context);
super.setClickable(true);
_context = context;
_scaleDetector = new ScaleGestureDetector(context, new ScaleListener());
_arrayOf9Floats = new float[9];
setScaleType(ScaleType.MATRIX);
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return handleTouch(v, event);
}
});
}
private boolean handleTouch(View v, MotionEvent event)
{
_scaleDetector.onTouchEvent(event);
//Contrary to how this line looks, the matrix is not setting the values from the arrayOf9Floats, but rather taking the
//matrix values and assigning them into the arrayOf9Floats. I extremely dislike this syntax and I think
//it should have been written as _arrayOf9Floats = _matrix.getValues() but that's Android for you!!!
_matrix.getValues(_arrayOf9Floats);
//Look at https://youtu.be/IiXB6tYtY4w?t=4m12s , it shows scale, rotate, and translate matrices
//If you look at the translate matrix, you'll see that the 3rd and 6th values are the values which represent x and y translations respectively
//this corresponds to the 2nd and 5th values in the array and hence why the MTRANS_X and MTRANS_Y have the constants 2 and 5 respectively
float xTranslate = _arrayOf9Floats[Matrix.MTRANS_X];
float yTranslate = _arrayOf9Floats[Matrix.MTRANS_Y];
PointF currentEventPoint = new PointF(event.getX(), event.getY());
switch (event.getAction())
{
//First finger down only
case MotionEvent.ACTION_DOWN:
_previousPoint.set(event.getX(), event.getY());
_startPoint.set(_previousPoint);
_mode = DRAG_MODE;
break;
//Second finger down
case MotionEvent.ACTION_POINTER_DOWN:
_previousPoint.set(event.getX(), event.getY());
_startPoint.set(_previousPoint);
_mode = ZOOM_MODE;
break;
case MotionEvent.ACTION_MOVE:
if (_mode == ZOOM_MODE || _mode == DRAG_MODE )
{
float deltaX = currentEventPoint.x - _previousPoint.x;
float deltaY = currentEventPoint.y - _previousPoint.y;
//In matrix terms, going right is + and going left is +
//Moving the image right past 0 means it will show alpha space on the left so we dont want that
//Keep in mind this is a TOP LEFT pivot point, so we dont want the top left to be past 0 lest we have alpha space
if(xTranslate + deltaX > 0)
{
//get absolute of how much into the negative we would have gone
float excessDeltaX = Math.abs(xTranslate + deltaX);
//take that excess away from deltaX so X wont got less than 0 after the translation
deltaX = deltaX - excessDeltaX;
}
//Going left we dont want the negative value to be less than the negative width of the sprite, lest we get alpha space on the right
//The width is going to be the width of the bitmap * scale and we want the - of it because we are checking for left movement
//We also need to account for the width of the DISPLAY CONTAINER (i.e. _displayWidth) so that gets subtracted
//i.e. we want the max scroll width value
float maxScrollableWidth = _bitmapWidth * _currentScale - _displayWidth;
if(xTranslate + deltaX < -maxScrollableWidth)
{
//this forces the max possible translate to always match the - of maxScrollableWidth
deltaX = -maxScrollableWidth - xTranslate;
}
//repeat for Y
if(yTranslate + deltaY > 0)
{
float excessDeltaY = Math.abs(yTranslate + deltaY);
deltaY = deltaY - excessDeltaY;
}
float maxScrollableHeight = _bitmapHeight * _currentScale - _displayWidth;
if(yTranslate + deltaY < -maxScrollableHeight)
{
//this forces the max possible translate to always match the - of maxScrollableWidth
deltaY = -maxScrollableHeight - yTranslate;
}
_matrix.postTranslate(deltaX, deltaY);
_matrix.getValues(_arrayOf9Floats);
//System.out.println(_matrix);
_previousPoint.set(currentEventPoint.x, currentEventPoint.y);
}
break;
case MotionEvent.ACTION_POINTER_UP:
_mode = NONE_MODE;
break;
}
setImageMatrix(_matrix);
invalidate();
return true;
}
#Override
public void setImageBitmap(Bitmap bm)
{
super.setImageBitmap(bm);
_bitmapWidth = bm.getWidth();
_bitmapHeight = bm.getHeight();
invalidate();
}
#Override
public void setImageResource(int resid)
{
Bitmap bitmapImage = BitmapFactory.decodeResource(_context.getResources(), resid);
setImageBitmap(bitmapImage);
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
#Override
public boolean onScaleBegin(ScaleGestureDetector detector)
{
_mode = ZOOM_MODE;
return true;
}
#Override
public boolean onScale(ScaleGestureDetector detector)
{
float scaleFactor = detector.getScaleFactor();
float originalScale = _currentScale;
_currentScale *= scaleFactor;
//Zoom in too much
if (_currentScale > _maxScale) {
_currentScale = _maxScale;
scaleFactor = _maxScale / originalScale;
}//Zoom out too much
else if (_currentScale < _minScale) {
_currentScale = _minScale;
scaleFactor = _minScale / originalScale;
}
_matrix.postScale(scaleFactor,scaleFactor);
return true;
}
}
#Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
_displayWidth = MeasureSpec.getSize(widthMeasureSpec);
_displayHeight = MeasureSpec.getSize(heightMeasureSpec);
adjustScale();
}
private void adjustScale()
{
//Fit to display bounds with NO alpha space
float scale;
float scaleX = _displayWidth / _bitmapWidth;
float scaleY = _displayHeight / _bitmapHeight;
scale = Math.max(scaleX, scaleY);
_matrix.setScale(scale, scale);
setImageMatrix(_matrix);
_currentScale = scale;
_minScale = scale;
}
public void setMaxZoom(float maxZoom){_maxScale = maxZoom;}
public void setMinZoom(float minZoom) {_minScale = minZoom;}
}
This code works and implement the double tap to return to original image size.
1st step - In your xml layout put this:
<com.****.*****.TouchImageView
android:id="#+id/action_infolinks_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#mipmap/myinfolinks_splash"
android:layout_gravity="center"
android:gravity="center"
android:scaleType="fitCenter"
android:contentDescription="#string/aboutSupport_description_image"/>
2nd step- Create a file (TouchImageView.java) with the TouchImageView class:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class TouchImageView extends ImageView {
Matrix matrix;
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF last = new PointF();
PointF start = new PointF();
float minScale = 1f;
float maxScale = 3f;
float[] m;
float redundantXSpace, redundantYSpace, origRedundantXSpace, origRedundantYSpace;
int viewWidth, viewHeight;
static final int CLICK = 3;
static final float SAVE_SCALE = 1f;
float saveScale = SAVE_SCALE;
protected float origWidth, origHeight;
int oldMeasuredWidth, oldMeasuredHeight;
float origScale, bottom, origBottom, right, origRight;
ScaleGestureDetector mScaleDetector;
GestureDetector mGestureDetector;
Context context;
public TouchImageView(Context context) {
super(context);
sharedConstructing(context);
}
public TouchImageView(Context context, AttributeSet attrs) {
super(context, attrs);
sharedConstructing(context);
}
private void sharedConstructing(Context context) {
super.setClickable(true);
this.context = context;
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
matrix = new Matrix();
m = new float[9];
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
boolean onDoubleTapEvent = mGestureDetector.onTouchEvent(event);
if (onDoubleTapEvent) {
// Reset Image to original scale values
mode = NONE;
bottom = origBottom;
right = origRight;
last = new PointF();
start = new PointF();
m = new float[9];
saveScale = SAVE_SCALE;
matrix = new Matrix();
matrix.setScale(origScale, origScale);
matrix.postTranslate(origRedundantXSpace, origRedundantYSpace);
setImageMatrix(matrix);
invalidate();
return true;
}
mScaleDetector.onTouchEvent(event);
PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
last.set(curr);
start.set(last);
mode = DRAG;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
float deltaX = curr.x - last.x;
float deltaY = curr.y - last.y;
float fixTransX = getFixDragTrans(deltaX, viewWidth, origWidth * saveScale);
float fixTransY = getFixDragTrans(deltaY, viewHeight, origHeight * saveScale);
matrix.postTranslate(fixTransX, fixTransY);
fixTrans();
last.set(curr.x, curr.y);
}
break;
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(curr.x - start.x);
int yDiff = (int) Math.abs(curr.y - start.y);
if (xDiff < CLICK && yDiff < CLICK) performClick();
break;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(matrix);
invalidate();
return true; // indicate event was handled
}
});
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
return true;
}
});
}
public void setMaxZoom(float x) {
maxScale = x;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
#Override
public boolean onScale(ScaleGestureDetector detector) {
float mScaleFactor = detector.getScaleFactor();
//float mScaleFactor = (float) Math.min(Math.max(.95f, detector.getScaleFactor()), 1.05);
float origScale = saveScale;
saveScale *= mScaleFactor;
if (saveScale > maxScale) {
saveScale = maxScale;
mScaleFactor = maxScale / origScale;
} else if (saveScale < minScale) {
saveScale = minScale;
mScaleFactor = minScale / origScale;
}
right = viewWidth * saveScale - viewWidth - (2 * redundantXSpace * saveScale);
bottom = viewHeight * saveScale - viewHeight - (2 * redundantYSpace * saveScale);
if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight)
matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2);
else
matrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());
fixTrans();
return true;
}
}
void fixTrans() {
matrix.getValues(m);
float transX = m[Matrix.MTRANS_X];
float transY = m[Matrix.MTRANS_Y];
float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
float fixTransY = getFixTrans(transY, viewHeight, origHeight * saveScale);
if (fixTransX != 0 || fixTransY != 0)
matrix.postTranslate(fixTransX, fixTransY);
}
float getFixTrans(float trans, float viewSize, float contentSize) {
float minTrans, maxTrans;
if (contentSize <= viewSize) {
minTrans = 0;
maxTrans = viewSize - contentSize;
} else {
minTrans = viewSize - contentSize;
maxTrans = 0;
}
if (trans < minTrans)
return -trans + minTrans;
if (trans > maxTrans)
return -trans + maxTrans;
return 0;
}
float getFixDragTrans(float delta, float viewSize, float contentSize) {
if (contentSize <= viewSize) {
return 0;
}
return delta;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
viewWidth = MeasureSpec.getSize(widthMeasureSpec);
viewHeight = MeasureSpec.getSize(heightMeasureSpec);
//
// Rescales image on rotation
//
if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) return;
oldMeasuredHeight = viewHeight;
oldMeasuredWidth = viewWidth;
if (saveScale == 1) {
// Fit to screen.
float scale;
int bmWidth,bmHeight;
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.mipmap.myinfolinks_splash);
bmWidth = bm.getWidth();
bmHeight = bm.getHeight();
int w = bmWidth;
int h = bmHeight;
viewWidth = resolveSize(w, widthMeasureSpec);
viewHeight = resolveSize(h, heightMeasureSpec);
float scaleX = (float) viewWidth / (float) bmWidth;
float scaleY = (float) viewHeight / (float) bmHeight;
scale = Math.min(scaleX, scaleY);
matrix.setScale(scale, scale);
saveScale = SAVE_SCALE;
origScale = scale;
// Center the image
redundantYSpace = (float) viewHeight - (scale * (float) bmHeight);
redundantXSpace = (float) viewWidth - (scale * (float) bmWidth);
redundantYSpace /= (float) 2;
redundantXSpace /= (float) 2;
origRedundantXSpace = redundantXSpace;
origRedundantYSpace = redundantYSpace;
matrix.postTranslate(redundantXSpace, redundantYSpace);
origWidth = viewWidth - 2 * redundantXSpace;
origHeight = viewHeight - 2 * redundantYSpace;
right = viewWidth * saveScale - viewWidth - (2 * redundantXSpace * saveScale);
bottom = viewHeight * saveScale - viewHeight - (2 * redundantYSpace * saveScale);
origRight = right;
origBottom = bottom;
setImageMatrix(matrix);
}
fixTrans();
}
}
And finally, make the call in your main activity:
TouchImageView imgDisplay = (TouchImageView) messageView.findViewById(R.id.id_myImage);
imgDisplay.setMaxZoom(2f);
imgDisplay.setImageResource(R.drawable.myImage);
I saw lots of code and after my adjustments it's working. Enjoy!
Step 1:
First you add dependencies in build.gradle(Module:app) file.
dependencies {
implementation 'com.jsibbold:zoomage:1.2.0'
}
Step 2:
Next create a class
ImageFullScreenFragment.java
public class ImageFullScreenFragment{
private ZoomageView ImageZoomageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = null;
try {
view = inflater.inflate(R.layout.fragment_image_full_screen, container, false);
ImageZoomageView = view.findViewById(R.id.imageViewImageFullScreen);
ImageZoomageView.setImageResource(R.drawable.image);
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
Step 3 :
Next create a layout xml file
fragment_image_full_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.jsibbold.zoomage.ZoomageView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:zoomage_restrictBounds="false"
app:zoomage_animateOnReset="true"
app:zoomage_autoResetMode="UNDER"
app:zoomage_autoCenter="true"
app:zoomage_zoomable="true"
app:zoomage_translatable="true"
app:zoomage_minScale="0.6"
app:zoomage_maxScale="8"
android:id="#+id/imageViewImageFullScreen"
/>
</RelativeLayout>
OutPut:-
You should put the image in webview and work with that. Zoom in / out controls are available in webview.
http://xjaphx.wordpress.com/2011/09/18/using-webview-as-a-image-zoom-view-control/
http://androidforums.com/android-lounge/121522-how-display-image-sdcard-webview.html
Try the following:
package com.example.nwssugeoinformationmobileapplication;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.FloatMath;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnTouchListener {
private static final String TAG = "Touch";
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
private ImageView view;
private float[] matrixValues = new float[9];
private float maxZoom;
private float minZoom;
private float height;
private float width;
private RectF viewRect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost th = (TabHost) findViewById (R.id.tabhost);
th.setup();
TabSpec specs = th.newTabSpec("tag1");
specs.setContent(R.id.tab1);
specs.setIndicator("Map");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.tab2);
specs.setIndicator("Search");
th.addTab(specs);
view = (ImageView) findViewById(R.id.imageView1);
Drawable bitmap = getResources().getDrawable(R.drawable.map);
view.setImageDrawable(bitmap);
view.setOnTouchListener(this);
matrix.setTranslate(1f, 1f);
view.setImageMatrix(matrix);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
init();
}
}
private void init() {
maxZoom = 2;
minZoom = 1f;
height = view.getDrawable().getIntrinsicHeight();
width = view.getDrawable().getIntrinsicWidth();
viewRect = new RectF(0, 0, view.getWidth(), view.getHeight());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menus, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()== R.id.item1){
Log.d("Tracks", "Track Us was Clicked");
startActivity(new Intent (MainActivity.this, Tracklocation.class ));
}
if(item.getItemId()== R.id.item2){
Log.d("Updates", "Updates was Clicked");
startActivity(new Intent (MainActivity.this, Updates.class ));
}
if(item.getItemId()== R.id.item3){
Log.d("About Us", "About Us was Clicked");
startActivity(new Intent (MainActivity.this, Horoscope.class ));
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onTouch(View v, MotionEvent rawEvent) {
ImageView view = (ImageView) v;
view.setScaleType(ImageView.ScaleType.MATRIX);
dumpEvent(rawEvent);
// Handle touch events here...
switch (rawEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(rawEvent.getX(), rawEvent.getY());
Log.d(TAG, "mode=DRAG");
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(rawEvent);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, rawEvent);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
Log.d(TAG, "mode=NONE");
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
matrix.set(savedMatrix);
// limit pan
matrix.getValues(matrixValues);
float currentY = matrixValues[Matrix.MTRANS_Y];
float currentX = matrixValues[Matrix.MTRANS_X];
float currentScale = matrixValues[Matrix.MSCALE_X];
float currentHeight = height * currentScale;
float currentWidth = width * currentScale;
float dx = rawEvent.getX() - start.x;
float dy = rawEvent.getY() - start.y;
float newX = currentX+dx;
float newY = currentY+dy;
RectF drawingRect = new RectF(newX, newY, newX+currentWidth, newY+currentHeight);
float diffUp = Math.min(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top);
float diffDown = Math.max(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top);
float diffLeft = Math.min(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right);
float diffRight = Math.max(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right);
if(diffUp > 0 ){
dy +=diffUp;
}
if(diffDown < 0){
dy +=diffDown;
}
if( diffLeft> 0){
dx += diffLeft;
}
if(diffRight < 0){
dx += diffRight;
}
matrix.postTranslate(dx, dy);
} else if (mode == ZOOM) {
float newDist = spacing(rawEvent);
Log.d(TAG, "newDist=" + newDist);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale1 = newDist / oldDist;
matrix.getValues(matrixValues);
float currentScale = matrixValues[Matrix.MSCALE_X];
// limit zoom
if (scale1 * currentScale > maxZoom) {
scale1 = maxZoom / currentScale;
} else if (scale1 * currentScale < minZoom) {
scale1 = minZoom / currentScale;
}
matrix.postScale(scale1, scale1, mid.x, mid.y);
}
}
break;
}
view.setImageMatrix(matrix);
return true;
}
#SuppressWarnings("deprecation")
private void dumpEvent(MotionEvent event) {
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid ").append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";");
}
sb.append("]");
Log.d(TAG, sb.toString());
}
/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
/** Calculate the mid point of the first two fingers */
#SuppressLint("FloatMath")
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);
}
}
I needed something similar, but needed the ability to get the dimensions easily and also drag/drop. I based this off of the answer #Nicolas Tyler gave and modified it from there.
The features are pinch zoom in/out, long press to vibration/highlighted drag/drop.
To use it add this CustomZoomView class to your project.
public class CustomZoomView extends View implements View.OnTouchListener, View.OnLongClickListener{
private Paint mPaint;
Vibrator v;
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
static final int MOVE = 3;
private int mode = NONE;
Rect src;
Rect mTempDst = new Rect();
Rect dst = new Rect();
Bitmap mBitmap;
private int mBitmapWidth = -1;
private int mBitmapHeight = -1;
private PointF mStartPoint = new PointF();
private PointF mMiddlePoint = new PointF();
private PointF mStartDragPoint = new PointF();
private PointF mMovePoint = new PointF();
private float oldDist = 1f;
private float scale;
private float oldEventX = 0;
private float oldEventY = 0;
private float oldStartPointX = 0;
private float oldStartPointY = 0;
private int mViewWidth = -1;
private int mViewHeight = -1;
private boolean mDraggable = false;
public CustomZoomView(Context context) {
this(context, null, 0);
}
public CustomZoomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomZoomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setOnTouchListener(this);
this.setOnLongClickListener(this);
v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
mPaint = new Paint();
mPaint.setColorFilter(new PorterDuffColorFilter(Color.argb(100,255,255,255), PorterDuff.Mode.SRC_IN));
}
#Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mViewWidth = w;
mViewHeight = h;
}
public void setBitmap(Bitmap bitmap) {
if (bitmap != null) {
src = new Rect();
src.left = 0;
src.top = 0;
src.right = bitmap.getWidth();
src.bottom = bitmap.getHeight();
mBitmap = bitmap;
mBitmapWidth = bitmap.getWidth() * 1;
mBitmapHeight = bitmap.getHeight() * 1;
dst = new Rect();
dst.left = (mViewWidth / 2) - (mBitmapWidth / 2);
dst.top = (mViewHeight / 2) - (mBitmapHeight / 2);
dst.right = (mViewWidth / 2) + (mBitmapWidth / 2);
dst.bottom = (mViewHeight / 2) + (mBitmapHeight / 2);
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mStartPoint.set(event.getX(), event.getY());
mStartDragPoint.set(event.getX(), event.getY());
mTempDst.set(dst.left, dst.top, dst.right, dst.bottom);
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f) {
midPoint(mMiddlePoint, event);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
if (mode == ZOOM) {
mBitmapWidth = dst.right - dst.left;
mBitmapHeight = dst.bottom - dst.top;
}
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
mMovePoint.x = event.getX();
mMovePoint.y = event.getY();
drag(event);
} else if (mode == ZOOM) {
zoom(event);
} else if (mode == MOVE) {
move(event);
}
break;
}
return false;
}
public void move(MotionEvent event) {
int xChange = (int) (event.getX() - mStartPoint.x);
int yChange = (int) (event.getY() - mStartPoint.y);
dst.left = mTempDst.left + (xChange);
dst.top = mTempDst.top + (yChange);
dst.right = mTempDst.right + (xChange);
dst.bottom = mTempDst.bottom + (yChange);
invalidate();
}
public void drag(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
float spacingX = eventX - mStartDragPoint.x;
float spacingY = eventY - mStartDragPoint.y;
float newPositionLeft = (dst.left < 0 ? spacingX : spacingX * -1) + dst.left;
float newPositionRight = (spacingX) + dst.right;
float newPositionTop = (dst.top < 0 ? spacingY : spacingY * -1) + dst.top;
float newPositionBottom = (spacingY) + dst.bottom;
boolean x = true;
boolean y = true;
if (newPositionRight < 0.0f || newPositionLeft > 0.0f) {
if (newPositionRight < 0.0f && newPositionLeft > 0.0f) {
x = false;
} else {
eventX = oldEventX;
mStartDragPoint.x = oldStartPointX;
}
}
if (newPositionBottom < 0.0f || newPositionTop > 0.0f) {
if (newPositionBottom < 0.0f && newPositionTop > 0.0f) {
y = false;
} else {
eventY = oldEventY;
mStartDragPoint.y = oldStartPointY;
}
}
if (mDraggable) {
if (x) oldEventX = eventX;
if (y) oldEventY = eventY;
if (x) oldStartPointX = mStartDragPoint.x;
if (y) oldStartPointY = mStartDragPoint.y;
}
}
public void zoom(MotionEvent event) {
float newDist = spacing(event);
boolean in = newDist > oldDist;
if (!in && scale < .01f) {
return;
}
scale = newDist / oldDist;
int xChange = (int) ((mBitmapWidth * scale) / 2);
int yChange = (int) ((mBitmapHeight * scale) / 2);
if (xChange > 10 && yChange > 10) { //ADDED THIS TO KEEP IT FROM GOING INVERSE
int xMidPoint = ((dst.right - dst.left) / 2) + dst.left;
int yMidPoint = ((dst.bottom - dst.top) / 2) + dst.top;
dst.left = (int) (float) (xMidPoint - xChange);
dst.top = (int) (float) (yMidPoint - yChange);
dst.right = (int) (float) (xMidPoint + xChange);
dst.bottom = (int) (float) (yMidPoint + yChange);
}
invalidate();
}
/**
* Determine the space between the first two fingers
*/
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
/**
* 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);
}
#Override
public boolean onLongClick(View view) {
if (mode == DRAG) {
if ((mStartPoint.x > dst.left && mStartPoint.x < dst.right) && (mStartPoint.y < dst.bottom && mStartPoint.y > dst.top)
&& (mMovePoint.x > dst.left && mMovePoint.x < dst.right) && (mMovePoint.y < dst.bottom && mMovePoint.y > dst.top)) {
mode = MOVE;
v.vibrate(500);
}
}
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mode == MOVE) {
canvas.drawBitmap(mBitmap, src, dst, null);
canvas.drawBitmap(mBitmap, src, dst, mPaint);
} else {
canvas.drawBitmap(mBitmap, src, dst, null);
}
}
}
...then add this to your activity
CustomZoomView customImageView = (CustomZoomView) findViewById(R.id.customZoomView);
customImageView.setBitmap(yourBitmap);
...and this in your view in xml.
<your.package.name.CustomZoomView
android:id="#+id/customZoomView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:longClickable="true"/>
...and add this to your manifest
<uses-permission android:name="android.permission.VIBRATE"/>
Here is my solution, it is based on #alexbirkett's solution.
public class ZoomImageView extends ImageView {
// region . Static fields .
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
static final int CLICK = 3;
// endregion . Static fields .
// region . Fields .
private int mode = NONE;
private Matrix mMatrix = new Matrix();
private PointF mLastTouch = new PointF();
private PointF mStartTouch = new PointF();
private float minScale = 0.5f;
private float maxScale = 4f;
private float[] mCriticPoints;
private float mScale = 1f;
private float mRight;
private float mBottom;
private float mOriginalBitmapWidth;
private float mOriginalBitmapHeight;
private ScaleGestureDetector mScaleDetector;
//endregion . Fields .
// region . Ctor .
public ZoomImageView(Context context) {
super(context);
init(context);
}
public ZoomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ZoomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
// endregion . Ctor .
// region . Overrider .
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int bmHeight = getBmHeight();
int bmWidth = getBmWidth();
float width = getMeasuredWidth();
float height = getMeasuredHeight();
float scale = 1;
// If image is bigger then display fit it to screen.
if (width < bmWidth || height < bmHeight) {
scale = width > height ? height / bmHeight : width / bmWidth;
}
mMatrix.setScale(scale, scale);
mScale = 1f;
mOriginalBitmapWidth = scale * bmWidth;
mOriginalBitmapHeight = scale * bmHeight;
// Center the image
float redundantYSpace = (height - mOriginalBitmapHeight);
float redundantXSpace = (width - mOriginalBitmapWidth);
mMatrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
setImageMatrix(mMatrix);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mMatrix.getValues(mCriticPoints);
float translateX = mCriticPoints[Matrix.MTRANS_X];
float trnslateY = mCriticPoints[Matrix.MTRANS_Y];
PointF currentPoint = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
//when one finger is touching
//set the mode to DRAG
case MotionEvent.ACTION_DOWN:
mLastTouch.set(event.getX(), event.getY());
mStartTouch.set(mLastTouch);
mode = DRAG;
break;
//when two fingers are touching
//set the mode to ZOOM
case MotionEvent.ACTION_POINTER_DOWN:
mLastTouch.set(event.getX(), event.getY());
mStartTouch.set(mLastTouch);
mode = ZOOM;
break;
//when a finger moves
//If mode is applicable move image
case MotionEvent.ACTION_MOVE:
//if the mode is ZOOM or
//if the mode is DRAG and already zoomed
if (mode == ZOOM || (mode == DRAG && mScale > minScale)) {
// region . Move image.
float deltaX = currentPoint.x - mLastTouch.x;// x difference
float deltaY = currentPoint.y - mLastTouch.y;// y difference
float scaleWidth = Math.round(mOriginalBitmapWidth * mScale);// width after applying current scale
float scaleHeight = Math.round(mOriginalBitmapHeight * mScale);// height after applying current scale
// Move image to lef or right if its width is bigger than display width
if (scaleWidth > getWidth()) {
if (translateX + deltaX > 0) {
deltaX = -translateX;
} else if (translateX + deltaX < -mRight) {
deltaX = -(translateX + mRight);
}
} else {
deltaX = 0;
}
// Move image to up or bottom if its height is bigger than display height
if (scaleHeight > getHeight()) {
if (trnslateY + deltaY > 0) {
deltaY = -trnslateY;
} else if (trnslateY + deltaY < -mBottom) {
deltaY = -(trnslateY + mBottom);
}
} else {
deltaY = 0;
}
//move the image with the matrix
mMatrix.postTranslate(deltaX, deltaY);
//set the last touch location to the current
mLastTouch.set(currentPoint.x, currentPoint.y);
// endregion . Move image .
}
break;
//first finger is lifted
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(currentPoint.x - mStartTouch.x);
int yDiff = (int) Math.abs(currentPoint.y - mStartTouch.y);
if (xDiff < CLICK && yDiff < CLICK)
performClick();
break;
// second finger is lifted
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(mMatrix);
invalidate();
return true;
}
//endregion . Overrides .
// region . Privates .
private void init(Context context) {
super.setClickable(true);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
mCriticPoints = new float[9];
setImageMatrix(mMatrix);
setScaleType(ScaleType.MATRIX);
}
private int getBmWidth() {
Drawable drawable = getDrawable();
if (drawable != null) {
return drawable.getIntrinsicWidth();
}
return 0;
}
private int getBmHeight() {
Drawable drawable = getDrawable();
if (drawable != null) {
return drawable.getIntrinsicHeight();
}
return 0;
}
//endregion . Privates .
// region . Internal classes .
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
#Override
public boolean onScale(ScaleGestureDetector detector) {
float scaleFactor = detector.getScaleFactor();
float newScale = mScale * scaleFactor;
if (newScale < maxScale && newScale > minScale) {
mScale = newScale;
float width = getWidth();
float height = getHeight();
mRight = (mOriginalBitmapWidth * mScale) - width;
mBottom = (mOriginalBitmapHeight * mScale) - height;
float scaledBitmapWidth = mOriginalBitmapWidth * mScale;
float scaledBitmapHeight = mOriginalBitmapHeight * mScale;
if (scaledBitmapWidth <= width || scaledBitmapHeight <= height) {
mMatrix.postScale(scaleFactor, scaleFactor, width / 2, height / 2);
} else {
mMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
}
}
return true;
}
}
// endregion . Internal classes .
}
Method to call the About&support dialog
public void setupAboutSupport() {
try {
// The About&Support AlertDialog is active
activeAboutSupport=true;
View messageView;
int orientation=this.getResources().getConfiguration().orientation;
// Inflate the about message contents
messageView = getLayoutInflater().inflate(R.layout.about_support, null, false);
ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.MyCustomTheme_AlertDialog1);
AlertDialog.Builder builder = new AlertDialog.Builder(ctw);
builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle(R.string.action_aboutSupport);
builder.setView(messageView);
TouchImageView imgDisplay = (TouchImageView) messageView.findViewById(R.id.action_infolinks_about_support);
imgDisplay.setMaxZoom(3f);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.myinfolinks_about_support);
int imageWidth = bitmap.getWidth();
int imageHeight = bitmap.getHeight();
int newWidth;
// Calculate the new About_Support image width
if(orientation==Configuration.ORIENTATION_PORTRAIT ) {
// For 7" up to 10" tablets
//if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
if (SingletonMyInfoLinks.isTablet) {
// newWidth = widthScreen - (two borders of about_support layout and 20% of width Screen)
newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.2));
} else newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.1));
} else {
// For 7" up to 10" tablets
//if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
if (SingletonMyInfoLinks.isTablet) {
newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.5));
} else newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.3));
}
// Get the scale factor
float scaleFactor = (float)newWidth/(float)imageWidth;
// Calculate the new About_Support image height
int newHeight = (int)(imageHeight * scaleFactor);
// Set the new bitmap corresponding the adjusted About_Support image
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
// Rescale the image
imgDisplay.setImageBitmap(bitmap);
dialogAboutSupport = builder.show();
TextView textViewVersion = (TextView) dialogAboutSupport.findViewById(R.id.action_strVersion);
textViewVersion.setText(Html.fromHtml(getString(R.string.aboutSupport_text1)+" <b>"+versionName+"</b>"));
TextView textViewDeveloperName = (TextView) dialogAboutSupport.findViewById(R.id.action_strDeveloperName);
textViewDeveloperName.setText(Html.fromHtml(getString(R.string.aboutSupport_text2)+" <b>"+SingletonMyInfoLinks.developerName+"</b>"));
TextView textViewSupportEmail = (TextView) dialogAboutSupport.findViewById(R.id.action_strSupportEmail);
textViewSupportEmail.setText(Html.fromHtml(getString(R.string.aboutSupport_text3)+" "+SingletonMyInfoLinks.developerEmail));
TextView textViewCompanyName = (TextView) dialogAboutSupport.findViewById(R.id.action_strCompanyName);
textViewCompanyName.setText(Html.fromHtml(getString(R.string.aboutSupport_text4)+" "+SingletonMyInfoLinks.companyName));
Button btnOk = (Button) dialogAboutSupport.findViewById(R.id.btnOK);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogAboutSupport.dismiss();
}
});
dialogAboutSupport.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(final DialogInterface dialog) {
// the About & Support AlertDialog is closed
activeAboutSupport=false;
}
});
dialogAboutSupport.getWindow().setBackgroundDrawable(new ColorDrawable(SingletonMyInfoLinks.atualBackgroundColor));
/* Effect that image appear slower */
// Only the fade_in matters
AlphaAnimation fade_out = new AlphaAnimation(1.0f, 0.0f);
AlphaAnimation fade_in = new AlphaAnimation(0.0f, 1.0f);
AlphaAnimation a = false ? fade_out : fade_in;
a.setDuration(2000); // 2 sec
a.setFillAfter(true); // Maintain the visibility at the end of animation
// Animation start
ImageView img = (ImageView) messageView.findViewById(R.id.action_infolinks_about_support);
img.startAnimation(a);
} catch (Exception e) {
//Log.e(SingletonMyInfoLinks.appNameText +"-" + getLocalClassName() + ": ", e.getMessage());
}
}
Just change ACTION_MOVE_EVENT in Chirag Raval Answer to set ZOOM_IN LIMIT
float[] values = new float[9]; matrix.getValues(values);
//0.37047964 is limit for zoom in
if(values[Matrix.MSCALE_X]>0.37047964) {
matrix.set(savedMatrix);
matrix.postScale(scale, scale, mid.x, mid.y);
view.setImageMatrix(matrix);
}else if (scale>1){
matrix.set(savedMatrix);
matrix.postScale(scale, scale, mid.x, mid.y);
view.setImageMatrix(matrix);
}
I know it is a bit late for this answer, but I hope it helps someone.
I was looking for the same thing (Zoom using pinch, and dragging image) and I found this Android Developers Blog link.
Works perfect. No artifacts or what so ever. It uses ScaleGestureDetector.
ZoomLib Link: https://drive.google.com/uc?export=download&id=0B34PUThnUsjVaHpkaGk0Z1hSRU0
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummy_layout_for_zooming);// Activity layout
mZoomLinearLayout = (LinearLayout) findViewById(R.id.mZoomLinearLayout);// LinearLayout inside Activity layout
View v = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_for_zoom, null, false);// View wants to zoom
v.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
ZoomView zoomView = new ZoomView(this);// intialize lib
zoomView.addView(v);
mZoomLinearLayout.addView(zoomView);
}
I think why you want to zoom-in and zoom-out the image view is because your image view is small and zooming in the image there will not let the image come out of the image view. Instead, image starts disappearing from the boundaries while zooming in. So letting the image come out of the image while we zoom in is what you want I guess.
So there are two tricks (according to me) to achieve this-
Change the layout params of the image view to cover the whole outermost view or view group at runtime while we are about to zoom-in the image.
Make an expanded Image view or Full Image View (height and width = Outermost View or View Group) in xml file and set it's visibility to gone. When we are about to zoom-in the image, load the image from small Image View into full Img View, map the image in fullImgView to image in smallImgView and make it's view visible.
Trick no.1 does not work when the image View is nested very much inside other views (like in nested recycler view)
Trick no.2 works always :-)
Here is the implementation of trick no.2 -
public class ZoomOnTouchListener extends AppCompatActivity implements View.OnTouchListener {
private Matrix matrix = new Matrix();
private boolean isfullImgViewActive = false;
// above boolean gets true when when we firstly move 2 fingers on the smallImgView and in this case smallImgView gets invisible and fullImgView gets visible
// and false if smallImgView is visible and fullImgView is gone
private float[] matrixArray = new float[9];
private float orgScale;
private PointF start = new PointF();
private PointF prevP1 = new PointF();
private PointF prevP2 = new PointF();
private PointF mid = new PointF();
private float oldDist = 1f;
private ImageView mfullImgView;
private ImageView smallImgView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfullImgView = (ImageView)findViewById(R.id.imgView2);
mfullImgView.setVisibility(View.GONE);
smallImgView = (ImageView)findViewById(R.id.imgView);
smallImgView.setOnTouchListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
//Log.i("0", "OnTouch()");
if(v instanceof ImageView) {
ImageView imgView = (ImageView) v;
boolean isImgViewSmall = (imgView == smallImgView);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
//Log.i("T", "Motion Event: ACTION_DOWN");
if(isImgViewSmall)
start.set(event.getX(), event.getY());
prevP1.set(event.getX(), event.getY());
return true;
case MotionEvent.ACTION_POINTER_DOWN: //second finger and other fingers down
prevP1.set(event.getX(0), event.getY(0));
prevP2.set(event.getX(1), event.getY(1));
oldDist = spacing(event);
midPoint(mid, event);
break;
case MotionEvent.ACTION_MOVE: //it doesn't mean fingers are moved. In this case, all pointers which are active are batched together
// this case occurs after action_down or action_pointer_down
//Log.i("Tag", event.getX()+","+event.getY());
if(event.getPointerCount() == 2) {
PointF newMid = new PointF();
midPoint(newMid,event);
float newDist = spacing(event);
float scale = newDist/oldDist;
if( !isfullImgViewActive){ // is smallImgView is visible and mfullImgView is gone
Log.i("tag", "true");
isfullImgViewActive = true;
matrix.set(imgView.getImageMatrix()); //note:- do not write matrix = imgView.getImageMatrix() because it gives the smallImgView's matrix reference to the matrix variable and changes on matrix will reflect on smallImgView
matrix.getValues(matrixArray);
orgScale = matrixArray[0];
smallImgView.setVisibility(View.INVISIBLE);
mfullImgView.setImageDrawable(smallImgView.getDrawable());
mfullImgView.setScaleType(ImageView.ScaleType.MATRIX);
mfullImgView.setVisibility(View.VISIBLE);
//To map the image of mFullImgView to that of smallImgView we have to
// translate the mFullImgView's image
matrix.postTranslate(tx, ty);
/////////////NOTE///////////////
//here (tx,ty) are coordinates of top-left corner of smallimgView and
// they MUST be relative to the origin of Outermost view or view group
// where fullImgView is placed. So find tx,ty in your case by yourself
mfullImgView.setImageMatrix(matrix);
}
if(isImgViewSmall) {
matrix.postScale(scale, scale, mid.x + tx, mid.y + ty);
}
else{
matrix.postScale(scale, scale, mid.x, mid.y);
}
oldDist = newDist;
matrix.postTranslate(newMid.x - mid.x, newMid.y - mid.y);
matrix.getValues(matrixArray);
mid.set(newMid);
prevP1.set(event.getX(0), event.getY(0));
prevP2.set(event.getX(1), event.getY(1));
}
else if(event.getPointerCount() == 1 ){
if(isfullImgViewActive) {
matrix.postTranslate(event.getX() - prevP1.x, event.getY() - prevP1.y);
matrix.getValues(matrixArray);
}
prevP1.set(event.getX(0), event.getY(0));
}
break;
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
//Now if pointer of index 0 is lifted then pointer of index 1 will get index 0;
if(event.getActionIndex() == 0 && isfullImgViewActive){
Log.i("TAg", event.getActionIndex()+"");
prevP1.set(prevP2);
}
break;
case MotionEvent.ACTION_UP: // first finger lifted or all fingers are lifted
if(isImgViewSmall && !isfullImgViewActive) {
imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
int xDiff = (int) Math.abs(event.getX() - start.x);
int yDiff = (int) Math.abs(event.getY() - start.y);
if (xDiff == 0 && yDiff == 0) {
imgView.performClick();
return true;
}
}
if(isfullImgViewActive){
if(matrixArray[0] <= orgScale){ //matrixArray[0] is Scale.X value
mfullImgView.setOnTouchListener(null);
mfullImgView.setImageDrawable(null);
mfullImgView.setVisibility(View.GONE);
smallImgView.setOnTouchListener(this);
smallImgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
smallImgView.setVisibility(View.VISIBLE);
isfullImgViewActive = false;
}
else if(matrixArray[0] > orgScale && isImgViewSmall){ //if the imgView was smallImgView
smallImgView.setOnTouchListener(null);
smallImgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
smallImgView.setVisibility(View.GONE); // or View.INVISIBLE
mfullImgView.setOnTouchListener(this);
}
}
return true;
}
//end of Switch statement
if(isfullImgViewActive) { //active means visible
mfullImgView.setImageMatrix(matrix); // display the transformation on screen
}
return true; // indicate event was handled
}
else
return false;
}
private float spacing(MotionEvent event)
{
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
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);
}
}
NOTE:- Don't set OnClickListener to mfullImgView before setting onTouchListener to it. Setting that will let the fullImageView(if it is visible) steal the touch event of putting second finger down after lifting it for the first time because we want to let the smallImgView take all the touch events until all the fingers are lifted up for the first time.
I am Using this one it is working perfectly.
<your.packagename.MyZoomableImageViewTouch
android:id="#+id/mediaImage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="matrix"/>
My a MyZoomableImageViewTouch class is below:
public class MyZoomableImageViewTouch extends ImageViewTouch
{
static final float SCROLL_DELTA_THRESHOLD = 1.0f;
public MyZoomableImageViewTouch(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init();
}
public MyZoomableImageViewTouch(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyZoomableImageViewTouch(Context context)
{
super(context);
init();
}
private void init() {
View.OnTouchListener listener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (getScale() > 1f) {
getParent().requestDisallowInterceptTouchEvent(true);
} else {
getParent().requestDisallowInterceptTouchEvent(false);
}
return false;
}
};
setOnTouchListener(listener);
setDisplayType(DisplayType.FIT_TO_SCREEN);
}
#Override
protected float onDoubleTapPost(float scale, float maxZoom) {
if (scale != 1f) {
mDoubleTapDirection = 1;
return 1f;
}
if (mDoubleTapDirection == 1) {
mDoubleTapDirection = -1;
if ((scale + (mScaleFactor * 2)) <= maxZoom) {
return scale + mScaleFactor;
} else {
mDoubleTapDirection = -1;
return maxZoom;
}
} else {
mDoubleTapDirection = 1;
return 1f;
}
}
#Override
public boolean canScroll(int direction) {
RectF bitmapRect = getBitmapRect();
updateRect(bitmapRect, mScrollRect);
Rect imageViewRect = new Rect();
getGlobalVisibleRect(imageViewRect);
if (null == bitmapRect) {
return false;
}
if (Math.abs(bitmapRect.right - imageViewRect.right) < SCROLL_DELTA_THRESHOLD) {
if (direction < 0) {
return false;
}
}
if (Math.abs(bitmapRect.left - mScrollRect.left) < SCROLL_DELTA_THRESHOLD) {
if (direction > 0) {
return false;
}
}
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
if (getScale() == 1f) return false;
if (distanceX != 0 && !canScroll((int) -distanceX)) {
getParent().requestDisallowInterceptTouchEvent(false);
return false;
} else {
getParent().requestDisallowInterceptTouchEvent(true);
mUserScaled = true;
scrollBy(-distanceX, -distanceY);
invalidate();
return true;
}
}
}

Categories

Resources