Pinch to Zoom Android ImageView Tutorial
Hi and welcome to another tutorial from Codingdemos, today you will learn how to build pinch to zoom Android function on an ImageView using 3rd party library called PhotoView. The experience will be a lot similar to what you see today in social media apps.
You will be building an app that have an Android ImageView and a TextView, when you tap on the ImageView an Android Alertdialog will appear on the screen showing you the image in full size where you can pinch and zoom on the image itself.
By the end of this tutorial, you will have an app that looks like this. (Large preview)
In this tutorial we will be using the following:
- – Android studio version 3.0
– Android emulator Nexus 5 with API 26
– Minimum SDK API 16
– PhotoView 3rd party library
1- Open up Android Studio and create a new project and give it a name, in our case we’ve named it (ImageZoom), choose API 16 as the minimum SDK, then choose a blank activity, click “Finish” and wait for Android Studio to build your project.
Create new Android Studio project. (Large preview)
2- Open up build.gradle (Module:app) and add PhotoView library.
3- Now you need to open up build.gradle (Project) and you need to add this line maven < url "https://jitpack.io" >inside (allprojects) tag.
4- Sync the project by clicking on (Sync Now).
Android studio sync gradle file. (Large preview)
5- Open activity_main.xml file, here you will add 3 views:
– Android ImageView that will hold the picture.
– Android TextView for the image title and description.
6- Add Android ImageView and make sure that you have added the image that you want to use for the ImageView inside the project drawable folder.
Android ImageView with image. (Large preview)
7- Reduce the size of the ImageView by adjusting android:layout_width and android:layout_height
Adjust width and height of Android ImageView. (Large preview)
8- Add some margin above the ImageView and place it in the center.
Android ImageView placed in the center with margin. (Large preview)
9- When you tap on the ImageView inside Android Studio preview window, you will see an empty space from top and bottom of the ImageView. You can fix that by using android:scaleType=»centerCrop» which allow the image to fill the remaining space.
Android ImageView with scaletype. (Large preview)
10- Add Android TextView which will hold the name of the picture, this TextView will be placed below ImageView (ivIcon) in the center, add some margin from the top, try to increase text size to (20sp) and change text style to (italic and bold).
11- Now you add the final TextView for this layout which will hold the description about the picture, this TextView will be placed below (tvName), try to increase text size to (16sp) and don’t forget to add some margin from the top so that it doesn’t appear to close with (tvName) TextView.
Flower title and description. (Large preview)
12- Now you are done working on activity_main.xml file, next you need to open up MainActivity.java file and initialize Android ImageView and Android AlertDialog.
13- Initialize ImageView (ivIcon).
14- Next you need to change the shape of ImageView (ivIcon) to circle using RoundedBitmapDrawable and Bitmap .
15- Build and run the app to see the progress.
Changed the shape of ImageView (ivIcon) to circle. (Large preview)
16- Now you need to work on Android AlertDialog, the AlertDialog will appear on the screen when you try to tap on ImageView (ivIcon). Before you start that, you first need to create another layout file that you will use it later for AlertDialog.
17- Create a new layout file and name it (dialog_custom_layout.xml), this file will have a PhotoView that will match the width and height of the screen.
18- Now go back to MainActivity.java file, to be able to tap on the ImageView you will need to use setOnClickListener and inside onClick is where you will create AlertDialog.
19- Build and run the app to test out Android pinch and zoom function.
PhotoView image doesn’t completely fill out AlertDialog. (Large preview)
20- Hmm it seems that the image doesn’t fill the entire AlertDialog! You can actually fix it by using android:scaleType=»centerCrop» .
21- Build and run the app to see the result.
PhotoView image appears inside AlertDialog. (Large preview)
22- Great now you have a fully working app with pinch to zoom Android function 🙂
The source code for this tutorial is available on GitHub, I hope you find this tutorial helpful and if you have any question please post them in the comment below.
Источник
Android studio zoom image
This is a great tutorial
I am using this code in fragments but
java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.ZoomControls.setOnZoomInClickListener(android.view.View$OnClickListener)’
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;
import abdulrehman.islamictasawwufsilsalanaqshbandiyaowaisia.R;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;
/**
* A simple <@link Fragment>subclass.
*/
public class HomeFragment extends Fragment <
TextView textView;
ImageView imageView;
ZoomControls simpleZoomControls;
public HomeFragment() <
// Required empty public constructor
>
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) <
View view =inflater.inflate(R.layout.fragment_home, container, false);
final ImageView imageView = view.findViewById(R.id.HazratJeeIntro1);
ImageView imageView1 = view.findViewById(R.id.hazrajee1);
PhotoViewAttacher photoView2 = new PhotoViewAttacher(imageView1);
photoView2.update();
final TextView textView = view.findViewById(R.id.HazratJeeDescEng);
imageView.setOnTouchListener(new View.OnTouchListener() <
@Override
public boolean onTouch(View v, MotionEvent event) <
simpleZoomControls.show();
return false;
>
>);
// perform setOnZoomInClickListener event on ZoomControls
simpleZoomControls.setOnZoomInClickListener(new View.OnClickListener() <
@Override
public void onClick(View v) <
// calculate current scale x and y value of ImageView
float x = imageView.getScaleX();
float y = imageView.getScaleY();
// set increased value of scale x and y to perform zoom in functionality
imageView.setScaleX((float) (x + 1));
imageView.setScaleY((float) (y + 1));
// display a toast to show Zoom In Message on Screen
Toast.makeText(getContext(),”Zoom In”,Toast.LENGTH_SHORT).show();
// hide the ZoomControls from the screen
simpleZoomControls.hide();
>
>);
// perform setOnZoomOutClickListener event on ZoomControls
simpleZoomControls.setOnZoomOutClickListener(new View.OnClickListener() <
@Override
public void onClick(View v) <
// calculate current scale x and y value of ImageView
float x = imageView.getScaleX();
float y = imageView.getScaleY();
// set decreased value of scale x and y to perform zoom out functionality
imageView.setScaleX((float) (x – 1));
imageView.setScaleY((float) (y – 1));
// display a toast to show Zoom Out Message on Screen
Toast.makeText(getContext(),”Zoom Out”,Toast.LENGTH_SHORT).show();
// hide the ZoomControls from the screen
simpleZoomControls.hide();
>
>);
return view;
>
>
sir how i can implement these zoom controls in textview. /
Источник
Implement Zoom In or Zoom Out in Android
Zoom In and Zoom Out animations are used to enlarge and reduce the size of a view in Android applications respectively. These types of animations are often used by developers to provide a dynamic nature to the applications. Users also feel the changes happening in the application by watching these kinds of animations.
XML Attributes of Scale Tag
The characteristics of Zoom In and Zoom Out animations are defined in the XML files by using scale tag.
XML attribute | Description |
---|---|
android:duration | Used to define the duration of the animation in millisecond |
android:fromXScale | Used to set initial size of the view in X-axis |
android:fromYScale | Used to set initial size of the view in Y-axis |
android:pivotX | To define the X coordinate of the point about which the object is being zoom in/out |
android:pivotY | To define the Y coordinate of the point about which the object is being zoom in/out |
android:toXScale | Used to set final size of the view in X-axis |
android:toYScale | Used to set final size of the view in Y-axis |
How to Add Zoom In/Out Animation in Android
The following example demonstrates the steps involved in implementing Zoom In and Zoom Out animation to an image file. An image file will be added in the activity using ImageView.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Create new project
- Click on File, then New => New Project.
- Select language as Kotlin.
- Select the minimum SDK as per your need.
Источник
Android studio zoom image
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 studio zoom image
A simple and customizable full-screen image viewer with shared image transition support, «pinch to zoom» and «swipe to dismiss» gestures. Compatible with all of the most popular image processing libraries such as Picasso , Glide etc. Based on PhotoView by chrisbanes.
Need iOS and Android apps, MVP development or prototyping? Contact us via info@stfalcon.com. We develop software since 2009, and we’re known experts in this field. Check out our portfolio and see more libraries from stfalcon-studio.
- A project configured with the AndroidX
- SDK 19 and and higher
Download via Gradle:
Add this to the project build.gradle file:
And then add the dependency to the module build.gradle file:
Download via Maven:
Where the latest_version is the value from Download badge.
All you need to show the viewer is to pass the context, list or array of your image objects and the implementation of the ImageLoader and call the show() method:
To improve the UX of your app you would like to add a transition when a user opens the viewer. And this is simple as never before! Just tell the viewer which image should be used for animation using withTransitionFrom(myImageView) method and the library will do it for you!
If you need more advanced behavior like updating transition target while changing images in the viewer please see the sample app for how to do this.
Update images list on the fly
There are a lot of common cases (such as pagination, deleting, editing etc.) where you need to update the existing images list while the viewer is running. To do this you can simply update the existing list (or even replace it with a new one) and then call updateImages(images) .
Change current image
Images are not always leafed through by the user. Maybe you want to implement some kind of preview list at the bottom of the viewer — setCurrentPosition is here for help. Change images programmatically wherever you want!
Custom overlay view
If you need to show some content over the image (e.g. sharing or download button, description, numeration etc.) you can set your own custom view using the setOverlayView(customView) and bind it with the viewer through the ImageViewer.OnImageChangeListener .
Use the setBackgroundColorRes(colorRes) or setBackgroundColor(colorInt) to set a color of the fading background.
Simply add margins between images using the withImagesMargin(context, dimenRes) method for dimensions, or use the withImageMarginPixels(int) for pixels size.
Overlay image hides part of the images? Set container padding with dimens using withContainerPadding(context, start, top, end, bottom) or withContainerPadding(context, dimen) for all of the sides evenly. For setting a padding in pixels, just use the withContainerPadding(. ) methods variant.
Status bar visibility
Control the status bar visibility of the opened viewer by using the withHiddenStatusBar(boolean) method ( true by default)
If you need to disable some of the gestures — you can use the allowSwipeToDismiss(boolean) and allowZooming(boolean) methods accordingly.
Here is the example with all of the existing options applied:
Also, you can take a look at the sample project for more information.
Usage with Fresco
If you use the Fresco library — check out the FrescoImageViewer which was also developed by our team.
About
A simple and customizable Android full-screen image viewer with shared image transition support, «pinch to zoom» and «swipe to dismiss» gestures
Источник