Pinch to zoom android

anorth / ZoomLayout.java

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

package au.id.alexn ;
import android.content.Context ;
import android.util.AttributeSet ;
import android.util.Log ;
import android.view.MotionEvent ;
import android.view.ScaleGestureDetector ;
import android.view.View ;
import android.widget.FrameLayout ;
/**
* Layout that provides pinch-zooming of content. This view should have exactly one child
* view containing the content.
*/
public class ZoomLayout extends FrameLayout implements ScaleGestureDetector . OnScaleGestureListener <
private enum Mode <
NONE ,
DRAG ,
ZOOM
>
private static final String TAG = » ZoomLayout » ;
private static final float MIN_ZOOM = 1.0f ;
private static final float MAX_ZOOM = 4.0f ;
private Mode mode = Mode . NONE ;
private float scale = 1.0f ;
private float lastScaleFactor = 0f ;
// Where the finger first touches the screen
private float startX = 0f ;
private float startY = 0f ;
// How much to translate the canvas
private float dx = 0f ;
private float dy = 0f ;
private float prevDx = 0f ;
private float prevDy = 0f ;
public ZoomLayout ( Context context ) <
super (context);
init(context);
>
public ZoomLayout ( Context context , AttributeSet attrs ) <
super (context, attrs);
init(context);
>
public ZoomLayout ( Context context , AttributeSet attrs , int defStyle ) <
super (context, attrs, defStyle);
init(context);
>
private void init ( Context context ) <
final ScaleGestureDetector scaleDetector = new ScaleGestureDetector (context, this );
this . setOnTouchListener( new View . OnTouchListener () <
@Override
public boolean onTouch ( View view , MotionEvent motionEvent ) <
switch (motionEvent . getAction() & MotionEvent . ACTION_MASK ) <
case MotionEvent . ACTION_DOWN :
Log . i( TAG , » DOWN » );
if (scale > MIN_ZOOM ) <
mode = Mode . DRAG ;
startX = motionEvent . getX() — prevDx;
startY = motionEvent . getY() — prevDy;
>
break ;
case MotionEvent . ACTION_MOVE :
if (mode == Mode . DRAG ) <
dx = motionEvent . getX() — startX;
dy = motionEvent . getY() — startY;
>
break ;
case MotionEvent . ACTION_POINTER_DOWN :
mode = Mode . ZOOM ;
break ;
case MotionEvent . ACTION_POINTER_UP :
mode = Mode . DRAG ;
break ;
case MotionEvent . ACTION_UP :
Log . i( TAG , » UP » );
mode = Mode . NONE ;
prevDx = dx;
prevDy = dy;
break ;
>
scaleDetector . onTouchEvent(motionEvent);
if ((mode == Mode . DRAG && scale >= MIN_ZOOM ) || mode == Mode . ZOOM ) <
getParent() . requestDisallowInterceptTouchEvent( true );
float maxDx = (child() . getWidth() — (child() . getWidth() / scale)) / 2 * scale;
float maxDy = (child() . getHeight() — (child() . getHeight() / scale)) / 2 * scale;
dx = Math . min( Math . max(dx, — maxDx), maxDx);
dy = Math . min( Math . max(dy, — maxDy), maxDy);
Log . i( TAG , » Width: » + child() . getWidth() + » , scale » + scale + » , dx » + dx
+ » , max » + maxDx);
applyScaleAndTranslation();
>
return true ;
>
>);
>
// ScaleGestureDetector
@Override
public boolean onScaleBegin ( ScaleGestureDetector scaleDetector ) <
Log . i( TAG , » onScaleBegin » );
return true ;
>
@Override
public boolean onScale ( ScaleGestureDetector scaleDetector ) <
float scaleFactor = scaleDetector . getScaleFactor();
Log . i( TAG , » onScale » + scaleFactor);
if (lastScaleFactor == 0 || ( Math . signum(scaleFactor) == Math . signum(lastScaleFactor))) <
scale *= scaleFactor;
scale = Math . max( MIN_ZOOM , Math . min(scale, MAX_ZOOM ));
lastScaleFactor = scaleFactor;
> else <
lastScaleFactor = 0 ;
>
return true ;
>
@Override
public void onScaleEnd ( ScaleGestureDetector scaleDetector ) <
Log . i( TAG , » onScaleEnd » );
>
private void applyScaleAndTranslation () <
child() . setScaleX(scale);
child() . setScaleY(scale);
child() . setTranslationX(dx);
child() . setTranslationY(dy);
>
private View child () <
return getChildAt( 0 );
>
>
Читайте также:  Обзор ip телефонии для андроид

This comment has been minimized.

Copy link Quote reply

jpfolador commented Sep 25, 2014

Do you have some example of how use your class?
Does it work with all layout? When you pinch the screen all objects get zoom (text, images, . ) ?
Thanks for your attention.

This comment has been minimized.

Copy link Quote reply

madhan123 commented Nov 21, 2014

When adding custom view to framelayout zoomlayout class not firing

Источник

Android — Pinch Zoom

To download the code, login with one of the following social providers.

Login Login

Be patient. we are fetching your source code.

Objective

You will get Final Output:

Step 1 Import needed .jar files

First we need following Jar files imagezoom.jar

Download from the given link: imagezoom.jar

Step 2 Import Java Files

Add jar files to your Android Project from the given Path ProjectName >> libs

Step 3 ImageView_Main.java file

Now Start Coding for the Pinch-Zoom Image. Create new class file named ImageView_Main.java and put following code into class.

Step 4 image_view.xml file

Create image_view.xml file. ImageView Declare as bellow in the image_view.xml file

I hope you enjoy this tutorial and it would be helpful to you.

Got an Idea of Android App Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Android App Development Company in India.

Tejas Jasani

An entrepreneur who has founded 2 flourishing software firms in 7 years, Tejas is keen to understand everything about gaming — from the business dynamics to awesome designs to gamer psychology. As the founder-CEO of a company that has released some very successful games, he knows a thing or two about gaming. He shares his knowledge through blogs and talks that he gets invited to.

Источник

Android Pinch Zoom Layout Example

Pinch zoom ( in or out ) is an often-used gesture in android applications. It is very user-friendly and smooth to display something bigger or smaller to watch. This example will show you how to implement pinch zoom on an image in the android application.

Читайте также:  Режим отладки андроид для чего

1. Make Android App Pinch Zoom Enabled Steps.

  1. Create a class like OnPinchListner which extends ScaleGestureDetector.SimpleOnScaleGestureListener. This class will be used to monitor user pinch-zoom gestures.
  2. Override the onScale(ScaleGestureDetector detector) method of OnPinchListner class, this method will be invoked when the listener detects pinch-zoom gesture.
  3. Create class android.view.ScaleGestureDetector‘s object scaleGestureDetector with an instance of class OnPinchListener as the constructor input parameter.
  4. When the activity on touch event occurred, invoke scaleGestureDetector‘s onTouchEvent method to make it detect scale change gesture.

2. Android Pinch Zoom Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/iALniC31f5M

  1. There is an image view widget in this example.
  2. When you run the example in the emulator. Click the control key ( Windows ) or command key ( Mac OS) and the left mouse key anywhere on the screen at the same time, you can zoom in and out the image.

Источник

Pinch to zoom android

A simple pinch-to-zoom ImageView library for Android with an emphasis on a smooth and natural feel.

Simply add a ZoomageView as you would any typical ImageView in Android. The scaleType that you set on your ZoomageView will determine the starting size and position of your ZoomageView’s image. This is the inherited ImageView.ScaleType from Android. With a ZoomageView, the fitCenter or centerInside scale types usually make the most sense to use, fitCenter being Android’s default scale type.

If using a ZoomageView with a view pager, it is recommended that ViewPager2 is used.

Restricts the bounds of the image so it does not wander outside the border of the ImageView when it’s smaller than the frame size, and restricts the bounds to stop at the edges of the ImageView when the image is larger than the frame size. Default value is false.

Image will animate back to its starting size whenever it is reset if true, and will snap back to its starting size when false. Default value is true.

Determines at what times the image will reset to its starting size. Note that UNDER, OVER, and ALWAYS all have the effect of resetting the image to its starting position if its size has not changed. Default value is UNDER.

This will cause the image to pull itself into view on-screen if it is partially off-screen. Default value is true.

The minimum allowed scale for the image. Ideally this should be less than 1, must be greater than 0, and must be less than maxScale. Default value is 0.6.

The maximum allowed scale for the image. Ideally this should be greater than 1, must be greater than 0, and must be greater than minScale. Default value is 8.

Читайте также:  Как н айфон может быть андроид

Sets whether zooming is allowed. Default value is true.

Sets whether translation is allowed. Default value is true.

Sets whether double tap to zoom functionality is enabled. Default is true.

Sets the scale factor for double tap to zoom functionality. Default is 3.

Special thanks to @mchowning for all his help

Источник

Изображение изображения на экране Android Pinch Zoom

Я использую пример кода из Ощущения мультитача для увеличения изображения. В ScaleListener я добавил ScaleGestureDetector.getFocusX() and getFocusY() для контента, чтобы увеличить фокусную точку жеста. Работает нормально.

Проблема в том, что при первом мультитаче все положение рисования изображения меняется на текущую точку касания и масштабируется оттуда. Не могли бы вы помочь мне решить эту проблему?

Вот мой пример кода для TouchImageView.

А вот как я использовал это в своей деятельности.

ОТВЕТЫ

Ответ 1

и не забудьте установить свойство scaleType в матрицу тега ImageView , например:

и используемые переменные:

Ответ 2

Вы можете использовать этот класс: TouchImageView

Ответ 3

Я сделал собственное собственное изображение с максимальным увеличением. Нет ограничений/границ на Chirag Raval, поэтому пользователь может перетащить изображение с экрана. Это исправит это.

Вот класс CustomImageView:

Вот как вы можете использовать его в своей деятельности:

Ответ 4

Добавьте строку ниже в build.gradle:

Ответ 5

Использование ScaleGestureDetector

При изучении новой концепции я не люблю использовать библиотеки или дампы кода. здесь и в документации я нашел подробное описание того, как изменить размер изображения, нажав. Этот ответ является слегка измененным резюме. Возможно, вы захотите добавить больше функциональности позже, но это поможет вам начать работу.

Компоновка

ImageView просто использует логотип приложения, поскольку он уже доступен. Вы можете заменить его любым изображением, которое вам нравится.

активность

Мы используем ScaleGestureDetector на активности, чтобы прослушивать сенсорные события. При обнаружении жеста масштабирования (т.е. сжатия) масштабный коэффициент используется для изменения размера ImageView .

Notes

    Хотя в приведенном выше примере у действия был детектор жестов, его также можно было установить в самом представлении изображения.

Вы можете ограничить размер масштабирования чем-то вроде

  • Документация
  • Используйте Ctrl + перетаскивание мышью для имитации жеста повышения в эмуляторе.
  • Продолжая

    Возможно, вы захотите заняться другими вещами, такими как панорамирование и масштабирование до некоторой точки фокусировки. Вы можете сами разработать эти вещи, но если вы хотите использовать готовый пользовательский вид, скопируйте TouchImageView.java в свой проект и используйте его как обычный ImageView . Это хорошо сработало для меня, и я столкнулся только с одной ошибкой. Я планирую дополнительно отредактировать код, чтобы удалить предупреждение и ненужные части. Вы можете сделать то же самое.

    Ответ 6

    Я сделал код для просмотра изображений с пинч для увеличения с помощью zoomageview. Таким образом, пользователь может перетащить изображение с экрана и увеличить, уменьшить изображение.

    Вы можете следовать этому link , чтобы получить код Step By Step , а также получить скриншот вывода.

    Источник

    Оцените статью