├── .gitignore ├── .idea ├── .name ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── scopes │ └── scope_settings.xml └── vcs.xml ├── LLongImageView.iml ├── README.md ├── app ├── .gitignore ├── app.iml ├── build.gradle ├── libs │ └── disklrucache-2.0.2.jar ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── xiaofan │ │ └── llongimageview │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── assets │ └── long.jpg │ ├── java │ └── xiaofan │ │ └── llongimageview │ │ ├── MyActivity.java │ │ └── view │ │ ├── CacheManager.java │ │ ├── ImageViewState.java │ │ ├── SubsamplingScaleImageView.java │ │ └── Utils.java │ └── res │ ├── drawable-hdpi │ └── ic_launcher.png │ ├── drawable-mdpi │ └── ic_launcher.png │ ├── drawable-xhdpi │ └── ic_launcher.png │ ├── drawable-xxhdpi │ └── ic_launcher.png │ ├── layout │ └── activity_my.xml │ ├── menu │ └── my.xml │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── attrs.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── demo.gif ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | LLongImageView -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Android API 17 Platform 14 | 15 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/scopes/scope_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /LLongImageView.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | LLongImageView 2 | ============== 3 | 4 | longer than longer ImageView 5 | 6 | why 7 | ============== 8 | 9 | User's phone have different size of photos include the long image. but the android ImageView can't display them. eg the 4096 px height or width.the most popular app like WeChat,Sina weibo can display well. I spend too much time and finally make that happen. 10 | Special thanks to the great project https://github.com/davemorrissey/subsampling-scale-image-view this project was based on it. 11 | 12 | 13 | how 14 | ============== 15 | I copy the based on project and add a few sample features. 16 | 17 | 1.Support remote url display 18 | 19 | 2.scale width to fit screen 20 | 21 | 3.add cache support 22 | 23 | so you can use it to display a image via assets, folder storage or url. 24 | just call setImageAsset(String name),setImageFile(String path),setImageUrl(String url,LLongImageLoadingListener longLoadingListener) 25 | if you want fit screen. 26 | call setFitScreen(true) before start loading. 27 | 28 | demo 29 | ============== 30 | ![image](https://github.com/xiaofans/LLongImageView/blob/master/demo.gif) 31 | 32 | 33 | TODO 34 | ============== 35 | make below api level 10 work 36 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 17 5 | buildToolsVersion "20.0.0" 6 | 7 | defaultConfig { 8 | applicationId "xiaofan.llongimageview" 9 | minSdkVersion 8 10 | targetSdkVersion 17 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | runProguard false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | compile 'com.android.support:appcompat-v7:20.0.0' 25 | compile files('libs/disklrucache-2.0.2.jar') 26 | } 27 | -------------------------------------------------------------------------------- /app/libs/disklrucache-2.0.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaofans/LLongImageView/3106f6791dc8a380428462564a242dc4afe07d77/app/libs/disklrucache-2.0.2.jar -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Android\android-studio1\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/xiaofan/llongimageview/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package xiaofan.llongimageview; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /app/src/main/assets/long.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaofans/LLongImageView/3106f6791dc8a380428462564a242dc4afe07d77/app/src/main/assets/long.jpg -------------------------------------------------------------------------------- /app/src/main/java/xiaofan/llongimageview/MyActivity.java: -------------------------------------------------------------------------------- 1 | package xiaofan.llongimageview; 2 | 3 | import android.app.Activity; 4 | import android.app.ProgressDialog; 5 | import android.os.Bundle; 6 | import android.view.Menu; 7 | import android.view.MenuItem; 8 | import android.widget.Toast; 9 | 10 | import xiaofan.llongimageview.view.SubsamplingScaleImageView; 11 | 12 | 13 | public class MyActivity extends Activity { 14 | 15 | private SubsamplingScaleImageView imageView; 16 | 17 | @Override 18 | protected void onCreate(Bundle savedInstanceState) { 19 | super.onCreate(savedInstanceState); 20 | setContentView(R.layout.activity_my); 21 | setUpViews(); 22 | } 23 | 24 | private void setUpViews() { 25 | imageView = (SubsamplingScaleImageView) findViewById(R.id.large_imageview_local); 26 | imageView.setFitScreen(true); 27 | imageView.setImageUrl("http://ww1.sinaimg.cn/bmiddle/61e9ece0gw1ekolcnx770j20c8c2akjm.jpg",new SubsamplingScaleImageView.LLongImageLoadingListener() { 28 | 29 | private ProgressDialog dialog; 30 | @Override 31 | public void loadingStart() { 32 | if(dialog == null) { 33 | dialog = new ProgressDialog(MyActivity.this); 34 | dialog.setTitle("Tip"); 35 | dialog.setMessage("Loading.."); 36 | } 37 | dialog.show(); 38 | } 39 | 40 | @Override 41 | public void loadingComplete() { 42 | dialog.dismiss(); 43 | } 44 | 45 | @Override 46 | public void loadingFailed() { 47 | dialog.dismiss(); 48 | Toast.makeText(MyActivity.this,"Load failed",Toast.LENGTH_LONG).show(); 49 | } 50 | }); 51 | } 52 | 53 | @Override 54 | public void onWindowFocusChanged(boolean hasFocus) { 55 | super.onWindowFocusChanged(hasFocus); 56 | } 57 | 58 | @Override 59 | public boolean onCreateOptionsMenu(Menu menu) { 60 | getMenuInflater().inflate(R.menu.my, menu); 61 | return true; 62 | } 63 | 64 | @Override 65 | public boolean onOptionsItemSelected(MenuItem item) { 66 | int id = item.getItemId(); 67 | if (id == R.id.action_settings) { 68 | return true; 69 | } 70 | return super.onOptionsItemSelected(item); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /app/src/main/java/xiaofan/llongimageview/view/CacheManager.java: -------------------------------------------------------------------------------- 1 | package xiaofan.llongimageview.view; 2 | 3 | import android.content.Context; 4 | 5 | import com.jakewharton.disklrucache.DiskLruCache; 6 | 7 | import java.io.ByteArrayInputStream; 8 | import java.io.ByteArrayOutputStream; 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | import java.io.OutputStream; 12 | 13 | /** 14 | * Created by zhaoyu on 2014/9/26. 15 | */ 16 | 17 | public class CacheManager { 18 | // LruCache 内存缓存 19 | // DiskLruCache 磁盘缓存 20 | private static final String CACHE_FOLDER = "long_image_cache"; 21 | // Default disk cache size 22 | private static final long DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; 23 | private int APP_VERSION = 1; 24 | private int VALUE_COUNT = 1; 25 | 26 | private DiskLruCache cache; 27 | private Context context; 28 | 29 | private CacheManager(Context c){ 30 | this.context = c.getApplicationContext(); 31 | try { 32 | cache = DiskLruCache.open(Utils.getDiskCacheDir(context,CACHE_FOLDER),APP_VERSION,VALUE_COUNT,DEFAULT_DISK_CACHE_SIZE); 33 | } catch (IOException e) { 34 | e.printStackTrace(); 35 | } 36 | } 37 | private static CacheManager cacheManager; 38 | 39 | public static synchronized CacheManager getInstance(Context context){ 40 | if(cacheManager == null) cacheManager = new CacheManager(context); 41 | return cacheManager; 42 | } 43 | 44 | public InputStream saveCache(String key,InputStream inputStream){ 45 | if(inputStream == null) return null; 46 | DiskLruCache.Editor editor = null; 47 | OutputStream ops = null; 48 | try { 49 | editor = cache.edit(key); 50 | if(editor == null) return inputStream; 51 | ops = editor.newOutputStream(0); 52 | ByteArrayOutputStream os=new ByteArrayOutputStream(); 53 | byte[] buffer = new byte[4 * 1024]; 54 | int numread; 55 | while ((numread = inputStream.read(buffer)) != -1){ 56 | os.write(buffer,0,numread); 57 | ops.write(buffer,0,numread); 58 | } 59 | InputStream is2 = new ByteArrayInputStream(os.toByteArray()); 60 | editor.commit(); 61 | return is2; 62 | } catch (IOException e) { 63 | e.printStackTrace(); 64 | } 65 | return null; 66 | } 67 | 68 | public InputStream get(String key){ 69 | DiskLruCache.Snapshot snapshot; 70 | try { 71 | snapshot = cache.get(key); 72 | if(snapshot == null) return null; 73 | return snapshot.getInputStream(0); 74 | } catch (IOException e) { 75 | e.printStackTrace(); 76 | } 77 | return null; 78 | } 79 | 80 | public void clearCache(){ 81 | try { 82 | cache.delete(); 83 | } catch (IOException e) { 84 | e.printStackTrace(); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /app/src/main/java/xiaofan/llongimageview/view/ImageViewState.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 David Morrissey 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package xiaofan.llongimageview.view; 18 | 19 | import android.graphics.PointF; 20 | 21 | import java.io.Serializable; 22 | 23 | /** 24 | * Wraps the scale, center and orientation of a displayed image for easy restoration on screen rotate. 25 | */ 26 | public class ImageViewState implements Serializable { 27 | 28 | private float scale; 29 | 30 | private float centerX; 31 | 32 | private float centerY; 33 | 34 | private int orientation; 35 | 36 | public ImageViewState(float scale, PointF center, int orientation) { 37 | this.scale = scale; 38 | this.centerX = center.x; 39 | this.centerY = center.y; 40 | this.orientation = orientation; 41 | } 42 | 43 | public float getScale() { 44 | return scale; 45 | } 46 | 47 | public PointF getCenter() { 48 | return new PointF(centerX, centerY); 49 | } 50 | 51 | public int getOrientation() { 52 | return orientation; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /app/src/main/java/xiaofan/llongimageview/view/SubsamplingScaleImageView.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 David Morrissey 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package xiaofan.llongimageview.view; 18 | 19 | import android.annotation.TargetApi; 20 | import android.content.Context; 21 | import android.content.res.AssetManager; 22 | import android.content.res.TypedArray; 23 | import android.graphics.*; 24 | import android.graphics.Bitmap.Config; 25 | import android.graphics.Paint.Style; 26 | import android.media.ExifInterface; 27 | import android.os.AsyncTask; 28 | import android.os.Build; 29 | import android.os.Build.VERSION; 30 | import android.os.Handler; 31 | import android.os.Message; 32 | import android.util.AttributeSet; 33 | import android.util.DisplayMetrics; 34 | import android.util.FloatMath; 35 | import android.util.Log; 36 | import android.view.GestureDetector; 37 | import android.view.MotionEvent; 38 | import android.view.View; 39 | 40 | import org.apache.http.client.methods.HttpGet; 41 | import org.apache.http.impl.client.DefaultHttpClient; 42 | 43 | import java.io.IOException; 44 | import java.io.InputStream; 45 | import java.lang.ref.WeakReference; 46 | import java.util.*; 47 | 48 | import javax.xml.transform.Source; 49 | 50 | import xiaofan.llongimageview.R; 51 | 52 | /** 53 | * Displays an image subsampled as necessary to avoid loading too much image data into memory. After a pinch to zoom in, 54 | * a set of image tiles subsampled at higher resolution are loaded and displayed over the base layer. During pinch and 55 | * zoom, tiles off screen or higher/lower resolution than required are discarded from memory. 56 | * 57 | * Tiles are no larger than the max supported bitmap size, so with large images tiling may be used even when zoomed out. 58 | * 59 | * v prefixes - coordinates, translations and distances measured in screen (view) pixels 60 | * s prefixes - coordinates, translations and distances measured in source image pixels (scaled) 61 | */ 62 | @SuppressWarnings("unused") 63 | public class SubsamplingScaleImageView extends View { 64 | 65 | private static final String TAG = SubsamplingScaleImageView.class.getSimpleName(); 66 | 67 | /** Attempt to use EXIF information on the image to rotate it. Works for external files only. */ 68 | public static final int ORIENTATION_USE_EXIF = -1; 69 | /** Display the image file in its native orientation. */ 70 | public static final int ORIENTATION_0 = 0; 71 | /** Rotate the image 90 degrees clockwise. */ 72 | public static final int ORIENTATION_90 = 90; 73 | /** Rotate the image 180 degrees. */ 74 | public static final int ORIENTATION_180 = 180; 75 | /** Rotate the image 270 degrees clockwise. */ 76 | public static final int ORIENTATION_270 = 270; 77 | 78 | private static final List VALID_ORIENTATIONS = Arrays.asList(ORIENTATION_0, ORIENTATION_90, ORIENTATION_180, ORIENTATION_270, ORIENTATION_USE_EXIF); 79 | 80 | /** During zoom animation, keep the point of the image that was tapped in the same place, and scale the image around it. */ 81 | public static final int ZOOM_FOCUS_FIXED = 1; 82 | /** During zoom animation, move the point of the image that was tapped to the center of the screen. */ 83 | public static final int ZOOM_FOCUS_CENTER = 2; 84 | /** Zoom in to and center the tapped point immediately without animating. */ 85 | public static final int ZOOM_FOCUS_CENTER_IMMEDIATE = 3; 86 | 87 | private static final List VALID_ZOOM_STYLES = Arrays.asList(ZOOM_FOCUS_FIXED, ZOOM_FOCUS_CENTER, ZOOM_FOCUS_CENTER_IMMEDIATE); 88 | 89 | /** Quadratic ease out. Not recommended for scale animation, but good for panning. */ 90 | public static final int EASE_OUT_QUAD = 1; 91 | /** Quadratic ease in and out. */ 92 | public static final int EASE_IN_OUT_QUAD = 2; 93 | 94 | private static final List VALID_EASING_STYLES = Arrays.asList(EASE_IN_OUT_QUAD, EASE_OUT_QUAD); 95 | 96 | /** Don't allow the image to be panned off screen. As much of the image as possible is always displayed, centered in the view when it is smaller. This is the best option for galleries. */ 97 | public static final int PAN_LIMIT_INSIDE = 1; 98 | /** Allows the image to be panned until it is just off screen, but no further. The edge of the image will stop when it is flush with the screen edge. */ 99 | public static final int PAN_LIMIT_OUTSIDE = 2; 100 | /** Allows the image to be panned until a corner reaches the center of the screen but no further. Useful when you want to pan any spot on the image to the exact center of the screen. */ 101 | public static final int PAN_LIMIT_CENTER = 3; 102 | 103 | private static final List VALID_PAN_LIMITS = Arrays.asList(PAN_LIMIT_INSIDE, PAN_LIMIT_OUTSIDE, PAN_LIMIT_CENTER); 104 | 105 | /** Scale the image so that both dimensions of the image will be equal to or less than the corresponding dimension of the view. The image is then centered in the view. This is the default behaviour and best for galleries. */ 106 | public static final int SCALE_TYPE_CENTER_INSIDE = 1; 107 | /** Scale the image uniformly so that both dimensions of the image will be equal to or larger than the corresponding dimension of the view. The image is then centered in the view. */ 108 | public static final int SCALE_TYPE_CENTER_CROP = 2; 109 | 110 | private static final List VALID_SCALE_TYPES = Arrays.asList(SCALE_TYPE_CENTER_CROP, SCALE_TYPE_CENTER_INSIDE); 111 | 112 | // Overlay tile boundaries and other info 113 | private boolean debug = false; 114 | 115 | // Image orientation setting 116 | private int orientation = ORIENTATION_0; 117 | 118 | // Max scale allowed (prevent infinite zoom) 119 | private float maxScale = 2F; 120 | 121 | // Density to reach before loading higher resolution tiles 122 | private int minimumTileDpi = -1; 123 | 124 | // Pan limiting style 125 | private int panLimit = PAN_LIMIT_INSIDE; 126 | 127 | // Minimum scale type 128 | private int minimumScaleType = SCALE_TYPE_CENTER_INSIDE; 129 | 130 | // Gesture detection settings 131 | private boolean panEnabled = true; 132 | private boolean zoomEnabled = true; 133 | 134 | // Double tap zoom behaviour 135 | private float doubleTapZoomScale = 1F; 136 | private int doubleTapZoomStyle = ZOOM_FOCUS_FIXED; 137 | 138 | // Current scale and scale at start of zoom 139 | private float scale; 140 | private float scaleStart; 141 | 142 | // Screen coordinate of top-left corner of source image 143 | private PointF vTranslate; 144 | private PointF vTranslateStart; 145 | 146 | // Source coordinate to center on, used when new position is set externally before view is ready 147 | private Float pendingScale; 148 | private PointF sPendingCenter; 149 | private PointF sRequestedCenter; 150 | 151 | // Source image dimensions and orientation - dimensions relate to the unrotated image 152 | private int sWidth; 153 | private int sHeight; 154 | private int sOrientation; 155 | 156 | // Is two-finger zooming in progress 157 | private boolean isZooming; 158 | // Is one-finger panning in progress 159 | private boolean isPanning; 160 | // Max touches used in current gesture 161 | private int maxTouchCount; 162 | 163 | // Fling detector 164 | private GestureDetector detector; 165 | 166 | // Tile decoder 167 | private BitmapRegionDecoder decoder; 168 | private final Object decoderLock = new Object(); 169 | 170 | // Sample size used to display the whole image when fully zoomed out 171 | private int fullImageSampleSize; 172 | 173 | // Map of zoom level to tile grid 174 | private Map> tileMap; 175 | 176 | // Debug values 177 | private PointF vCenterStart; 178 | private float vDistStart; 179 | 180 | // Scale and center animation tracking 181 | private Anim anim; 182 | 183 | // Whether a ready notification has been sent to subclasses 184 | private boolean readySent = false; 185 | 186 | // Long click listener 187 | private OnLongClickListener onLongClickListener; 188 | 189 | // Long click handler 190 | private Handler handler; 191 | private static final int MESSAGE_LONG_CLICK = 1; 192 | 193 | // Paint objects created once and reused for efficiency 194 | private Paint bitmapPaint; 195 | private Paint debugPaint; 196 | 197 | // is fit screen 198 | private boolean isFitScreen; 199 | 200 | public interface LLongImageLoadingListener{ 201 | void loadingStart(); 202 | void loadingComplete(); 203 | void loadingFailed(); 204 | } 205 | private LLongImageLoadingListener longImageLoadingListener; 206 | 207 | public LLongImageLoadingListener getLongImageLoadingListener() { 208 | return longImageLoadingListener; 209 | } 210 | 211 | public SubsamplingScaleImageView(Context context, AttributeSet attr) { 212 | super(context, attr); 213 | setMinimumDpi(160); 214 | setDoubleTapZoomDpi(160); 215 | setGestureDetector(context); 216 | this.handler = new Handler(new Handler.Callback() { 217 | public boolean handleMessage(Message message) { 218 | if (message.what == MESSAGE_LONG_CLICK && onLongClickListener != null) { 219 | maxTouchCount = 0; 220 | SubsamplingScaleImageView.super.setOnLongClickListener(onLongClickListener); 221 | performLongClick(); 222 | SubsamplingScaleImageView.super.setOnLongClickListener(null); 223 | } 224 | return true; 225 | } 226 | }); 227 | // Handle XML attributes 228 | if (attr != null) { 229 | TypedArray typedAttr = getContext().obtainStyledAttributes(attr, R.styleable.SubsamplingScaleImageView); 230 | if (typedAttr.hasValue(R.styleable.SubsamplingScaleImageView_assetName)) { 231 | String assetName = typedAttr.getString(R.styleable.SubsamplingScaleImageView_assetName); 232 | if (assetName != null && assetName.length() > 0) { 233 | setImageAsset(assetName); 234 | } 235 | } 236 | if (typedAttr.hasValue(R.styleable.SubsamplingScaleImageView_panEnabled)) { 237 | setPanEnabled(typedAttr.getBoolean(R.styleable.SubsamplingScaleImageView_panEnabled, true)); 238 | } 239 | if (typedAttr.hasValue(R.styleable.SubsamplingScaleImageView_zoomEnabled)) { 240 | setZoomEnabled(typedAttr.getBoolean(R.styleable.SubsamplingScaleImageView_zoomEnabled, true)); 241 | } 242 | } 243 | } 244 | 245 | public SubsamplingScaleImageView(Context context) { 246 | this(context, null); 247 | } 248 | 249 | /** 250 | * Sets the image orientation. It's best to call this before setting the image file or asset, because it may waste 251 | * loading of tiles. However, this can be freely called at any time. 252 | */ 253 | public final void setOrientation(int orientation) { 254 | if (!VALID_ORIENTATIONS.contains(orientation)) { 255 | throw new IllegalArgumentException("Invalid orientation: " + orientation); 256 | } 257 | this.orientation = orientation; 258 | reset(false); 259 | invalidate(); 260 | requestLayout(); 261 | } 262 | 263 | /** 264 | * Display an image from a file in internal or external storage. 265 | * @param extFile URI of the file to display. 266 | */ 267 | public final void setImageFile(String extFile) { 268 | reset(true); 269 | BitmapInitTask task = new BitmapInitTask(this, getContext(), extFile, BitmapInitTask.SourceType.FILE_PATH); 270 | task.execute(); 271 | invalidate(); 272 | } 273 | 274 | /** 275 | * Display an image from a file in internal or external storage, starting with a given orientation setting, scale 276 | * and center. This is the best method to use when you want scale and center to be restored after screen orientation 277 | * change; it avoids any redundant loading of tiles in the wrong orientation. 278 | * @param extFile URI of the file to display. 279 | * @param state State to be restored. Nullable. 280 | */ 281 | public final void setImageFile(String extFile, ImageViewState state) { 282 | reset(true); 283 | restoreState(state); 284 | BitmapInitTask task = new BitmapInitTask(this, getContext(), extFile, BitmapInitTask.SourceType.FILE_PATH); 285 | task.execute(); 286 | invalidate(); 287 | } 288 | 289 | /** 290 | * Display an image from a file in assets. 291 | * @param assetName asset name. 292 | */ 293 | public final void setImageAsset(String assetName) { 294 | setImageAsset(assetName, null); 295 | } 296 | 297 | /** 298 | * Display an image from a file in assets, starting with a given orientation setting, scale and center. This is the 299 | * best method to use when you want scale and center to be restored after screen orientation change; it avoids any 300 | * redundant loading of tiles in the wrong orientation. 301 | * @param url the image url. 302 | * @param state State to be restored. Nullable. 303 | */ 304 | public final void setImageUrl(String url, ImageViewState state,LLongImageLoadingListener listener) { 305 | this.longImageLoadingListener = listener; 306 | reset(true); 307 | restoreState(state); 308 | BitmapInitTask task = new BitmapInitTask(this, getContext(), url, BitmapInitTask.SourceType.URL); 309 | task.execute(); 310 | invalidate(); 311 | } 312 | 313 | /** 314 | * Display an image from a url. 315 | * @param url 316 | */ 317 | public final void setImageUrl(String url,LLongImageLoadingListener listener) { 318 | setImageUrl(url, null,listener); 319 | } 320 | 321 | /** 322 | * Display an image from a file in assets, starting with a given orientation setting, scale and center. This is the 323 | * best method to use when you want scale and center to be restored after screen orientation change; it avoids any 324 | * redundant loading of tiles in the wrong orientation. 325 | * @param assetName asset name. 326 | * @param state State to be restored. Nullable. 327 | */ 328 | public final void setImageAsset(String assetName, ImageViewState state) { 329 | reset(true); 330 | restoreState(state); 331 | BitmapInitTask task = new BitmapInitTask(this, getContext(), assetName, BitmapInitTask.SourceType.ASSET); 332 | task.execute(); 333 | invalidate(); 334 | } 335 | 336 | /** 337 | * Reset all state before setting/changing image or setting new rotation. 338 | */ 339 | @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) 340 | private void reset(boolean newImage) { 341 | scale = 0f; 342 | scaleStart = 0f; 343 | vTranslate = null; 344 | vTranslateStart = null; 345 | pendingScale = 0f; 346 | sPendingCenter = null; 347 | sRequestedCenter = null; 348 | isZooming = false; 349 | isPanning = false; 350 | maxTouchCount = 0; 351 | fullImageSampleSize = 0; 352 | vCenterStart = null; 353 | vDistStart = 0; 354 | anim = null; 355 | if (newImage) { 356 | if (decoder != null) { 357 | synchronized (decoderLock) { 358 | decoder.recycle(); 359 | decoder = null; 360 | } 361 | } 362 | sWidth = 0; 363 | sHeight = 0; 364 | sOrientation = 0; 365 | readySent = false; 366 | } 367 | if (tileMap != null) { 368 | for (Map.Entry> tileMapEntry : tileMap.entrySet()) { 369 | for (Tile tile : tileMapEntry.getValue()) { 370 | tile.visible = false; 371 | if (tile.bitmap != null) { 372 | tile.bitmap.recycle(); 373 | tile.bitmap = null; 374 | } 375 | } 376 | } 377 | tileMap = null; 378 | } 379 | } 380 | 381 | private void setGestureDetector(final Context context) { 382 | this.detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { 383 | @Override 384 | public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 385 | if (panEnabled && readySent && vTranslate != null && e1 != null && e2 != null && (Math.abs(e1.getX() - e2.getX()) > 50 || Math.abs(e1.getY() - e2.getY()) > 50) && (Math.abs(velocityX) > 500 || Math.abs(velocityY) > 500) && !isZooming) { 386 | PointF vTranslateEnd = new PointF(vTranslate.x + (velocityX * 0.25f), vTranslate.y + (velocityY * 0.25f)); 387 | float sCenterXEnd = ((getWidth()/2) - vTranslateEnd.x)/scale; 388 | float sCenterYEnd = ((getHeight()/2) - vTranslateEnd.y)/scale; 389 | new AnimationBuilder(new PointF(sCenterXEnd, sCenterYEnd)).withEasing(EASE_OUT_QUAD).withPanLimited(false).start(); 390 | return true; 391 | } 392 | return super.onFling(e1, e2, velocityX, velocityY); 393 | } 394 | 395 | @Override 396 | public boolean onSingleTapConfirmed(MotionEvent e) { 397 | performClick(); 398 | return true; 399 | } 400 | 401 | @Override 402 | public boolean onDoubleTap(MotionEvent e) { 403 | if (zoomEnabled && readySent && vTranslate != null) { 404 | float doubleTapZoomScale = Math.min(maxScale, SubsamplingScaleImageView.this.doubleTapZoomScale); 405 | boolean zoomIn = scale <= doubleTapZoomScale * 0.9; 406 | float targetScale = zoomIn ? doubleTapZoomScale : Math.min(getWidth() / (float) sWidth(), getHeight() / (float) sHeight()); 407 | PointF targetSCenter = viewToSourceCoord(new PointF(e.getX(), e.getY())); 408 | if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER_IMMEDIATE) { 409 | setScaleAndCenter(targetScale, targetSCenter); 410 | } else if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER || !zoomIn) { 411 | new AnimationBuilder(targetScale, targetSCenter).withInterruptible(false).start(); 412 | } else if (doubleTapZoomStyle == ZOOM_FOCUS_FIXED) { 413 | new AnimationBuilder(targetScale, targetSCenter, new PointF(e.getX(), e.getY())).withInterruptible(false).start(); 414 | } 415 | 416 | // Hacky solution for #15 - after a double tap the GestureDetector gets in a state where the next 417 | // fling is ignored, so here we replace it with a new one. 418 | setGestureDetector(context); 419 | 420 | invalidate(); 421 | return true; 422 | } 423 | return super.onDoubleTapEvent(e); 424 | } 425 | }); 426 | } 427 | 428 | /** 429 | * On resize, preserve center and scale. Various behaviours are possible, override this method to use another. 430 | */ 431 | @Override 432 | protected void onSizeChanged(int w, int h, int oldw, int oldh) { 433 | if (readySent) { 434 | setScaleAndCenter(getScale(), getCenter()); 435 | } 436 | } 437 | 438 | /** 439 | * Measures the width and height of the view, preserving the aspect ratio of the image displayed if wrap_content is 440 | * used. The image will scale within this box, not resizing the view as it is zoomed. 441 | */ 442 | @Override 443 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 444 | int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); 445 | int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); 446 | int parentWidth = MeasureSpec.getSize(widthMeasureSpec); 447 | int parentHeight = MeasureSpec.getSize(heightMeasureSpec); 448 | boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY; 449 | boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY; 450 | int width = parentWidth; 451 | int height = parentHeight; 452 | if (sWidth > 0 && sHeight > 0) { 453 | if (resizeWidth && resizeHeight) { 454 | width = sWidth(); 455 | height = sHeight(); 456 | } else if (resizeHeight) { 457 | height = (int)((((double)sHeight()/(double)sWidth()) * width)); 458 | } else if (resizeWidth) { 459 | width = (int)((((double)sWidth()/(double)sHeight()) * height)); 460 | } 461 | } 462 | width = Math.max(width, getSuggestedMinimumWidth()); 463 | height = Math.max(height, getSuggestedMinimumHeight()); 464 | setMeasuredDimension(width, height); 465 | } 466 | 467 | /** 468 | * Handle touch events. One finger pans, and two finger pinch and zoom plus panning. 469 | */ 470 | @Override 471 | public boolean onTouchEvent(MotionEvent event) { 472 | PointF vCenterEnd; 473 | float vDistEnd; 474 | // During non-interruptible anims, ignore all touch events 475 | if (anim != null && !anim.interruptible) { 476 | getParent().requestDisallowInterceptTouchEvent(true); 477 | return true; 478 | } else { 479 | anim = null; 480 | } 481 | 482 | // Abort if not ready 483 | if (vTranslate == null) { 484 | return true; 485 | } 486 | // Detect flings, taps and double taps 487 | if (detector == null || detector.onTouchEvent(event)) { 488 | return true; 489 | } 490 | 491 | int touchCount = event.getPointerCount(); 492 | switch (event.getAction()) { 493 | case MotionEvent.ACTION_DOWN: 494 | case MotionEvent.ACTION_POINTER_1_DOWN: 495 | case MotionEvent.ACTION_POINTER_2_DOWN: 496 | anim = null; 497 | getParent().requestDisallowInterceptTouchEvent(true); 498 | maxTouchCount = Math.max(maxTouchCount, touchCount); 499 | if (touchCount >= 2) { 500 | if (zoomEnabled) { 501 | // Start pinch to zoom. Calculate distance between touch points and center point of the pinch. 502 | float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); 503 | scaleStart = scale; 504 | vDistStart = distance; 505 | vTranslateStart = new PointF(vTranslate.x, vTranslate.y); 506 | vCenterStart = new PointF((event.getX(0) + event.getX(1))/2, (event.getY(0) + event.getY(1))/2); 507 | } else { 508 | // Abort all gestures on second touch 509 | maxTouchCount = 0; 510 | } 511 | // Cancel long click timer 512 | handler.removeMessages(MESSAGE_LONG_CLICK); 513 | } else { 514 | // Start one-finger pan 515 | vTranslateStart = new PointF(vTranslate.x, vTranslate.y); 516 | vCenterStart = new PointF(event.getX(), event.getY()); 517 | 518 | // Start long click timer 519 | handler.sendEmptyMessageDelayed(MESSAGE_LONG_CLICK, 600); 520 | } 521 | return true; 522 | case MotionEvent.ACTION_MOVE: 523 | boolean consumed = false; 524 | if (maxTouchCount > 0) { 525 | if (touchCount >= 2) { 526 | // Calculate new distance between touch points, to scale and pan relative to start values. 527 | vDistEnd = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); 528 | vCenterEnd = new PointF((event.getX(0) + event.getX(1))/2, (event.getY(0) + event.getY(1))/2); 529 | 530 | if (zoomEnabled && (distance(vCenterStart.x, vCenterEnd.x, vCenterStart.y, vCenterEnd.y) > 5 || Math.abs(vDistEnd - vDistStart) > 5 || isPanning)) { 531 | isZooming = true; 532 | isPanning = true; 533 | consumed = true; 534 | 535 | scale = Math.min(maxScale, (vDistEnd / vDistStart) * scaleStart); 536 | 537 | if (scale <= minScale()) { 538 | // Minimum scale reached so don't pan. Adjust start settings so any expand will zoom in. 539 | vDistStart = vDistEnd; 540 | scaleStart = minScale(); 541 | vCenterStart = vCenterEnd; 542 | vTranslateStart = vTranslate; 543 | } else if (panEnabled) { 544 | // Translate to place the source image coordinate that was at the center of the pinch at the start 545 | // at the center of the pinch now, to give simultaneous pan + zoom. 546 | float vLeftStart = vCenterStart.x - vTranslateStart.x; 547 | float vTopStart = vCenterStart.y - vTranslateStart.y; 548 | float vLeftNow = vLeftStart * (scale/scaleStart); 549 | float vTopNow = vTopStart * (scale/scaleStart); 550 | vTranslate.x = vCenterEnd.x - vLeftNow; 551 | vTranslate.y = vCenterEnd.y - vTopNow; 552 | } else if (sRequestedCenter != null) { 553 | // With a center specified from code, zoom around that point. 554 | vTranslate.x = (getWidth()/2) - (scale * sRequestedCenter.x); 555 | vTranslate.y = (getHeight()/2) - (scale * sRequestedCenter.y); 556 | } else { 557 | // With no requested center, scale around the image center. 558 | vTranslate.x = (getWidth()/2) - (scale * (sWidth()/2)); 559 | vTranslate.y = (getHeight()/2) - (scale * (sHeight()/2)); 560 | } 561 | 562 | fitToBounds(true); 563 | refreshRequiredTiles(false); 564 | } 565 | } else if (!isZooming) { 566 | // One finger pan - translate the image. We do this calculation even with pan disabled so click 567 | // and long click behaviour is preserved. 568 | float dx = Math.abs(event.getX() - vCenterStart.x); 569 | float dy = Math.abs(event.getY() - vCenterStart.y); 570 | if (dx > 5 || dy > 5 || isPanning) { 571 | consumed = true; 572 | vTranslate.x = vTranslateStart.x + (event.getX() - vCenterStart.x); 573 | vTranslate.y = vTranslateStart.y + (event.getY() - vCenterStart.y); 574 | 575 | float lastX = vTranslate.x; 576 | float lastY = vTranslate.y; 577 | fitToBounds(true); 578 | if (lastX == vTranslate.x || (lastY == vTranslate.y && dy > 10) || isPanning) { 579 | isPanning = true; 580 | } else if (dx > 5) { 581 | // Haven't panned the image, and we're at the left or right edge. Switch to page swipe. 582 | maxTouchCount = 0; 583 | handler.removeMessages(MESSAGE_LONG_CLICK); 584 | getParent().requestDisallowInterceptTouchEvent(false); 585 | } 586 | 587 | if (!panEnabled) { 588 | vTranslate.x = vTranslateStart.x; 589 | vTranslate.y = vTranslateStart.y; 590 | getParent().requestDisallowInterceptTouchEvent(false); 591 | } 592 | 593 | refreshRequiredTiles(false); 594 | } 595 | } 596 | } 597 | if (consumed) { 598 | handler.removeMessages(MESSAGE_LONG_CLICK); 599 | invalidate(); 600 | return true; 601 | } 602 | break; 603 | case MotionEvent.ACTION_UP: 604 | case MotionEvent.ACTION_POINTER_UP: 605 | case MotionEvent.ACTION_POINTER_2_UP: 606 | handler.removeMessages(MESSAGE_LONG_CLICK); 607 | if (maxTouchCount > 0 && (isZooming || isPanning)) { 608 | if (isZooming && touchCount == 2) { 609 | // Convert from zoom to pan with remaining touch 610 | isPanning = true; 611 | vTranslateStart = new PointF(vTranslate.x, vTranslate.y); 612 | if (event.getActionIndex() == 1) { 613 | vCenterStart = new PointF(event.getX(0), event.getY(0)); 614 | } else { 615 | vCenterStart = new PointF(event.getX(1), event.getY(1)); 616 | } 617 | } 618 | if (touchCount < 3) { 619 | // End zooming when only one touch point 620 | isZooming = false; 621 | } 622 | if (touchCount < 2) { 623 | // End panning when no touch points 624 | isPanning = false; 625 | maxTouchCount = 0; 626 | } 627 | // Trigger load of tiles now required 628 | refreshRequiredTiles(true); 629 | return true; 630 | } 631 | if (touchCount == 1) { 632 | isZooming = false; 633 | isPanning = false; 634 | maxTouchCount = 0; 635 | } 636 | return true; 637 | } 638 | return super.onTouchEvent(event); 639 | } 640 | 641 | @Override 642 | public void setOnLongClickListener(OnLongClickListener onLongClickListener) { 643 | this.onLongClickListener = onLongClickListener; 644 | } 645 | 646 | /** 647 | * Draw method should not be called until the view has dimensions so the first calls are used as triggers to calculate 648 | * the scaling and tiling required. Once the view is setup, tiles are displayed as they are loaded. 649 | */ 650 | @Override 651 | protected void onDraw(Canvas canvas) { 652 | super.onDraw(canvas); 653 | createPaints(); 654 | 655 | // If image or view dimensions are not known yet, abort. 656 | if (sWidth == 0 || sHeight == 0 || decoder == null || getWidth() == 0 || getHeight() == 0) { 657 | return; 658 | } 659 | 660 | // On first render with no tile map ready, initialise it and kick off async base image loading. 661 | if (tileMap == null) { 662 | initialiseBaseLayer(getMaxBitmapDimensions(canvas)); 663 | return; 664 | } 665 | 666 | // If waiting to translate to new center position, set translate now 667 | if (sPendingCenter != null && pendingScale != null) { 668 | scale = pendingScale; 669 | vTranslate.x = (getWidth()/2) - (scale * sPendingCenter.x); 670 | vTranslate.y = (getHeight()/2) - (scale * sPendingCenter.y); 671 | sPendingCenter = null; 672 | pendingScale = null; 673 | fitToBounds(true); 674 | refreshRequiredTiles(true); 675 | } 676 | 677 | // On first display of base image set up position, and in other cases make sure scale is correct. 678 | fitToBounds(false); 679 | 680 | // Everything is set up and coordinates are valid. Inform subclasses. 681 | if (!readySent) { 682 | readySent = true; 683 | new Thread(new Runnable() { 684 | public void run() { 685 | onImageReady(); 686 | } 687 | }).start(); 688 | } 689 | 690 | // If animating scale, calculate current scale and center with easing equations 691 | if (anim != null) { 692 | long scaleElapsed = System.currentTimeMillis() - anim.time; 693 | boolean finished = scaleElapsed > anim.duration; 694 | scaleElapsed = Math.min(scaleElapsed, anim.duration); 695 | scale = ease(anim.easing, scaleElapsed, anim.scaleStart, anim.scaleEnd - anim.scaleStart, anim.duration); 696 | 697 | // Apply required animation to the focal point 698 | float vFocusNowX = ease(anim.easing, scaleElapsed, anim.vFocusStart.x, anim.vFocusEnd.x - anim.vFocusStart.x, anim.duration); 699 | float vFocusNowY = ease(anim.easing, scaleElapsed, anim.vFocusStart.y, anim.vFocusEnd.y - anim.vFocusStart.y, anim.duration); 700 | // Find out where the focal point is at this scale and adjust its position to follow the animation path 701 | PointF vFocus = sourceToViewCoord(anim.sCenterEnd); 702 | vTranslate.x -= vFocus.x - vFocusNowX; 703 | vTranslate.y -= vFocus.y - vFocusNowY; 704 | 705 | // For translate anims, showing the image non-centered is never allowed, for scaling anims it is during the animation. 706 | fitToBounds(finished || (anim.scaleStart == anim.scaleEnd)); 707 | refreshRequiredTiles(finished); 708 | if (finished) { 709 | anim = null; 710 | } 711 | invalidate(); 712 | } 713 | 714 | // Optimum sample size for current scale 715 | int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize()); 716 | 717 | // First check for missing tiles - if there are any we need the base layer underneath to avoid gaps 718 | boolean hasMissingTiles = false; 719 | for (Map.Entry> tileMapEntry : tileMap.entrySet()) { 720 | if (tileMapEntry.getKey() == sampleSize) { 721 | for (Tile tile : tileMapEntry.getValue()) { 722 | if (tile.visible && (tile.loading || tile.bitmap == null)) { 723 | hasMissingTiles = true; 724 | } 725 | } 726 | } 727 | } 728 | 729 | // Render all loaded tiles. LinkedHashMap used for bottom up rendering - lower res tiles underneath. 730 | for (Map.Entry> tileMapEntry : tileMap.entrySet()) { 731 | if (tileMapEntry.getKey() == sampleSize || hasMissingTiles) { 732 | for (Tile tile : tileMapEntry.getValue()) { 733 | Rect vRect = convertRect(sourceToViewRect(tile.sRect)); 734 | if (!tile.loading && tile.bitmap != null) { 735 | canvas.drawBitmap(tile.bitmap, null, vRect, bitmapPaint); 736 | if (debug) { 737 | canvas.drawRect(vRect, debugPaint); 738 | } 739 | } else if (tile.loading && debug) { 740 | canvas.drawText("LOADING", vRect.left + 5, vRect.top + 35, debugPaint); 741 | } 742 | if (tile.visible && debug) { 743 | canvas.drawText("ISS " + tile.sampleSize + " RECT " + tile.sRect.top + "," + tile.sRect.left + "," + tile.sRect.bottom + "," + tile.sRect.right, vRect.left + 5, vRect.top + 15, debugPaint); 744 | } 745 | } 746 | } 747 | } 748 | 749 | if (debug) { 750 | canvas.drawText("Scale: " + String.format("%.2f", scale), 5, 15, debugPaint); 751 | canvas.drawText("Translate: " + String.format("%.2f", vTranslate.x) + ":" + String.format("%.2f", vTranslate.y), 5, 35, debugPaint); 752 | PointF center = getCenter(); 753 | canvas.drawText("Source center: " + String.format("%.2f", center.x) + ":" + String.format("%.2f", center.y), 5, 55, debugPaint); 754 | 755 | if (anim != null) { 756 | PointF vCenterStart = sourceToViewCoord(anim.sCenterStart); 757 | PointF vCenterEndRequested = sourceToViewCoord(anim.sCenterEndRequested); 758 | PointF vCenterEnd = sourceToViewCoord(anim.sCenterEnd); 759 | canvas.drawCircle(vCenterStart.x, vCenterStart.y, 10, debugPaint); 760 | canvas.drawCircle(vCenterEndRequested.x, vCenterEndRequested.y, 20, debugPaint); 761 | canvas.drawCircle(vCenterEnd.x, vCenterEnd.y, 25, debugPaint); 762 | canvas.drawCircle(getWidth()/2, getHeight()/2, 30, debugPaint); 763 | } 764 | } 765 | } 766 | 767 | /** 768 | * Creates Paint objects once when first needed. 769 | */ 770 | private void createPaints() { 771 | if (bitmapPaint == null) { 772 | bitmapPaint = new Paint(); 773 | bitmapPaint.setAntiAlias(true); 774 | bitmapPaint.setFilterBitmap(true); 775 | bitmapPaint.setDither(true); 776 | } 777 | if (debugPaint == null && debug) { 778 | debugPaint = new Paint(); 779 | debugPaint.setTextSize(18); 780 | debugPaint.setColor(Color.MAGENTA); 781 | debugPaint.setStyle(Style.STROKE); 782 | } 783 | } 784 | 785 | /** 786 | * Called on first draw when the view has dimensions. Calculates the initial sample size and starts async loading of 787 | * the base layer image - the whole source subsampled as necessary. 788 | */ 789 | private synchronized void initialiseBaseLayer(Point maxTileDimensions) { 790 | 791 | fitToBounds(true); 792 | 793 | // Load double resolution - next level will be split into four tiles and at the center all four are required, 794 | // so don't bother with tiling until the next level 16 tiles are needed. 795 | fullImageSampleSize = calculateInSampleSize(); 796 | if (fullImageSampleSize > 1) { 797 | fullImageSampleSize /= 2; 798 | } 799 | 800 | initialiseTileMap(maxTileDimensions); 801 | 802 | List baseGrid = tileMap.get(fullImageSampleSize); 803 | for (Tile baseTile : baseGrid) { 804 | BitmapTileTask task = new BitmapTileTask(this, decoder, decoderLock, baseTile); 805 | task.execute(); 806 | } 807 | 808 | } 809 | 810 | /** 811 | * Loads the optimum tiles for display at the current scale and translate, so the screen can be filled with tiles 812 | * that are at least as high resolution as the screen. Frees up bitmaps that are now off the screen. 813 | * @param load Whether to load the new tiles needed. Use false while scrolling/panning for performance. 814 | */ 815 | private void refreshRequiredTiles(boolean load) { 816 | int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize()); 817 | RectF vVisRect = new RectF(0, 0, getWidth(), getHeight()); 818 | RectF sVisRect = viewToSourceRect(vVisRect); 819 | 820 | // Load tiles of the correct sample size that are on screen. Discard tiles off screen, and those that are higher 821 | // resolution than required, or lower res than required but not the base layer, so the base layer is always present. 822 | for (Map.Entry> tileMapEntry : tileMap.entrySet()) { 823 | for (Tile tile : tileMapEntry.getValue()) { 824 | if (tile.sampleSize < sampleSize || (tile.sampleSize > sampleSize && tile.sampleSize != fullImageSampleSize)) { 825 | tile.visible = false; 826 | if (tile.bitmap != null) { 827 | tile.bitmap.recycle(); 828 | tile.bitmap = null; 829 | } 830 | } 831 | if (tile.sampleSize == sampleSize) { 832 | if (RectF.intersects(sVisRect, convertRect(tile.sRect))) { 833 | tile.visible = true; 834 | if (!tile.loading && tile.bitmap == null && load) { 835 | BitmapTileTask task = new BitmapTileTask(this, decoder, decoderLock, tile); 836 | task.execute(); 837 | } 838 | } else if (tile.sampleSize != fullImageSampleSize) { 839 | tile.visible = false; 840 | if (tile.bitmap != null) { 841 | tile.bitmap.recycle(); 842 | tile.bitmap = null; 843 | } 844 | } 845 | } else if (tile.sampleSize == fullImageSampleSize) { 846 | tile.visible = true; 847 | } 848 | } 849 | } 850 | 851 | } 852 | 853 | /** 854 | * Calculates sample size to fit the source image in given bounds. 855 | */ 856 | private int calculateInSampleSize() { 857 | float adjustedScale = scale; 858 | if (minimumTileDpi > 0) { 859 | DisplayMetrics metrics = getResources().getDisplayMetrics(); 860 | float averageDpi = (metrics.xdpi + metrics.ydpi)/2; 861 | adjustedScale = (minimumTileDpi/averageDpi) * scale; 862 | } 863 | 864 | int reqWidth = (int)(sWidth() * adjustedScale); 865 | int reqHeight = (int)(sHeight() * adjustedScale); 866 | 867 | // Raw height and width of image 868 | int inSampleSize = 1; 869 | if (reqWidth == 0 || reqHeight == 0) { 870 | return 32; 871 | } 872 | 873 | if (sHeight() > reqHeight || sWidth() > reqWidth) { 874 | 875 | // Calculate ratios of height and width to requested height and width 876 | final int heightRatio = Math.round((float) sHeight() / (float) reqHeight); 877 | final int widthRatio = Math.round((float) sWidth() / (float) reqWidth); 878 | 879 | // Choose the smallest ratio as inSampleSize value, this will guarantee 880 | // a final image with both dimensions larger than or equal to the 881 | // requested height and width. 882 | inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 883 | } 884 | 885 | // We want the actual sample size that will be used, so round down to nearest power of 2. 886 | int power = 1; 887 | while (power * 2 < inSampleSize) { 888 | power = power * 2; 889 | } 890 | 891 | return power; 892 | } 893 | 894 | /** 895 | * Adjusts hypothetical future scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale 896 | * is set so one dimension fills the view and the image is centered on the other dimension. Used to calculate what the target of an 897 | * animation should be. 898 | * @param center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached. 899 | * @param scaleAndTranslate The scale we want and the translation we're aiming for. The values are adjusted to be valid. 900 | */ 901 | private void fitToBounds(boolean center, ScaleAndTranslate scaleAndTranslate) { 902 | if (panLimit == PAN_LIMIT_OUTSIDE && isImageReady()) { 903 | center = false; 904 | } 905 | 906 | PointF vTranslate = scaleAndTranslate.translate; 907 | float scale = limitedScale(scaleAndTranslate.scale); 908 | float scaleWidth = scale * sWidth(); 909 | float scaleHeight = scale * sHeight(); 910 | 911 | if (panLimit == PAN_LIMIT_CENTER && isImageReady()) { 912 | vTranslate.x = Math.max(vTranslate.x, getWidth()/2 - scaleWidth); 913 | vTranslate.y = Math.max(vTranslate.y, getHeight()/2 - scaleHeight); 914 | } else if (center) { 915 | vTranslate.x = Math.max(vTranslate.x, getWidth() - scaleWidth); 916 | vTranslate.y = Math.max(vTranslate.y, getHeight() - scaleHeight); 917 | } else { 918 | vTranslate.x = Math.max(vTranslate.x, -scaleWidth); 919 | vTranslate.y = Math.max(vTranslate.y, -scaleHeight); 920 | } 921 | 922 | float maxTx; 923 | float maxTy; 924 | if (panLimit == PAN_LIMIT_CENTER && isImageReady()) { 925 | maxTx = Math.max(0, getWidth()/2); 926 | maxTy = Math.max(0, getHeight()/2); 927 | } else if (center) { 928 | maxTx = Math.max(0, (getWidth() - scaleWidth) / 2); 929 | maxTy = Math.max(0, (getHeight() - scaleHeight) / 2); 930 | } else { 931 | maxTx = Math.max(0, getWidth()); 932 | maxTy = Math.max(0, getHeight()); 933 | } 934 | 935 | vTranslate.x = Math.min(vTranslate.x, maxTx); 936 | vTranslate.y = Math.min(vTranslate.y, maxTy); 937 | 938 | scaleAndTranslate.scale = scale; 939 | } 940 | 941 | /** 942 | * Adjusts current scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale 943 | * is set so one dimension fills the view and the image is centered on the other dimension. 944 | * @param center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached. 945 | */ 946 | private void fitToBounds(boolean center) { 947 | boolean init = false; 948 | if (vTranslate == null) { 949 | init = true; 950 | vTranslate = new PointF(0, 0); 951 | } 952 | ScaleAndTranslate input = new ScaleAndTranslate(scale, vTranslate); 953 | fitToBounds(center, input); 954 | scale = input.scale; 955 | if (init) { 956 | vTranslate = vTranslateForSCenter(new PointF(sWidth()/2, sHeight()/2), scale); 957 | } 958 | } 959 | 960 | /** 961 | * Once source image and view dimensions are known, creates a map of sample size to tile grid. 962 | */ 963 | private void initialiseTileMap(Point maxTileDimensions) { 964 | this.tileMap = new LinkedHashMap>(); 965 | int sampleSize = fullImageSampleSize; 966 | int xTiles = 1; 967 | int yTiles = 1; 968 | while (true) { 969 | int sTileWidth = sWidth()/xTiles; 970 | int sTileHeight = sHeight()/yTiles; 971 | int subTileWidth = sTileWidth/sampleSize; 972 | int subTileHeight = sTileHeight/sampleSize; 973 | while (subTileWidth > maxTileDimensions.x || (subTileWidth > getWidth() * 1.25 && sampleSize < fullImageSampleSize)) { 974 | xTiles += 1; 975 | sTileWidth = sWidth()/xTiles; 976 | subTileWidth = sTileWidth/sampleSize; 977 | } 978 | while (subTileHeight > maxTileDimensions.y || (subTileHeight > getHeight() * 1.25 && sampleSize < fullImageSampleSize)) { 979 | yTiles += 1; 980 | sTileHeight = sHeight()/yTiles; 981 | subTileHeight = sTileHeight/sampleSize; 982 | } 983 | List tileGrid = new ArrayList(xTiles * yTiles); 984 | for (int x = 0; x < xTiles; x++) { 985 | for (int y = 0; y < yTiles; y++) { 986 | Tile tile = new Tile(); 987 | tile.sampleSize = sampleSize; 988 | tile.visible = sampleSize == fullImageSampleSize; 989 | tile.sRect = new Rect( 990 | x * sTileWidth, 991 | y * sTileHeight, 992 | (x + 1) * sTileWidth, 993 | (y + 1) * sTileHeight 994 | ); 995 | tileGrid.add(tile); 996 | } 997 | } 998 | tileMap.put(sampleSize, tileGrid); 999 | if (sampleSize == 1) { 1000 | break; 1001 | } else { 1002 | sampleSize /= 2; 1003 | } 1004 | } 1005 | } 1006 | 1007 | /** 1008 | * Called by worker task when decoder is ready and image size and EXIF orientation is known. 1009 | */ 1010 | private void onImageInited(BitmapRegionDecoder decoder, int sWidth, int sHeight, int sOrientation) { 1011 | this.decoder = decoder; 1012 | this.sWidth = sWidth; 1013 | this.sHeight = sHeight; 1014 | this.sOrientation = sOrientation; 1015 | if(isFitScreen){ 1016 | fitScreen(); 1017 | } 1018 | requestLayout(); 1019 | invalidate(); 1020 | } 1021 | 1022 | // fit the image to screen 1023 | private void fitScreen(){ 1024 | int screenWidth = getResources().getDisplayMetrics().widthPixels; 1025 | if(this.sWidth > screenWidth) return; 1026 | float scale = (float)screenWidth / (float)this.sWidth; 1027 | setScaleAndCenter(scale,new PointF(screenWidth / 2,0)); 1028 | } 1029 | 1030 | 1031 | /** 1032 | * Called by worker task when a tile has loaded. Redraws the view. 1033 | */ 1034 | private void onTileLoaded() { 1035 | invalidate(); 1036 | } 1037 | 1038 | 1039 | 1040 | 1041 | /** 1042 | * Async task used to get image details without blocking the UI thread. 1043 | */ 1044 | private static class BitmapInitTask extends AsyncTask { 1045 | private final WeakReference viewRef; 1046 | private final WeakReference contextRef; 1047 | private final String source; 1048 | private BitmapRegionDecoder decoder; 1049 | public enum SourceType{ 1050 | ASSET, 1051 | FILE_PATH, 1052 | URL 1053 | } 1054 | private SourceType sourceType; 1055 | 1056 | public BitmapInitTask(SubsamplingScaleImageView view, Context context, String source, SourceType sourceType) { 1057 | this.viewRef = new WeakReference(view); 1058 | this.contextRef = new WeakReference(context); 1059 | this.source = source; 1060 | this.sourceType = sourceType; 1061 | } 1062 | 1063 | @Override 1064 | protected void onPreExecute() { 1065 | super.onPreExecute(); 1066 | if(viewRef != null){ 1067 | final SubsamplingScaleImageView subsamplingScaleImageView = viewRef.get(); 1068 | if(subsamplingScaleImageView.getLongImageLoadingListener() != null){ 1069 | subsamplingScaleImageView.getLongImageLoadingListener().loadingStart(); 1070 | } 1071 | } 1072 | } 1073 | 1074 | @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) 1075 | @Override 1076 | protected int[] doInBackground(Void... params) { 1077 | try { 1078 | if (viewRef != null && contextRef != null) { 1079 | Context context = contextRef.get(); 1080 | if (context != null) { 1081 | int exifOrientation = ORIENTATION_0; 1082 | switch (sourceType){ 1083 | case ASSET: 1084 | decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(source, AssetManager.ACCESS_RANDOM), true); 1085 | break; 1086 | case FILE_PATH: 1087 | decoder = BitmapRegionDecoder.newInstance(source, true); 1088 | try { 1089 | ExifInterface exifInterface = new ExifInterface(source); 1090 | int orientationAttr = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 1091 | if (orientationAttr == ExifInterface.ORIENTATION_NORMAL) { 1092 | exifOrientation = ORIENTATION_0; 1093 | } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_90) { 1094 | exifOrientation = ORIENTATION_90; 1095 | } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_180) { 1096 | exifOrientation = ORIENTATION_180; 1097 | } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_270) { 1098 | exifOrientation = ORIENTATION_270; 1099 | } else { 1100 | Log.w(TAG, "Unsupported EXIF orientation: " + orientationAttr); 1101 | } 1102 | } catch (Exception e) { 1103 | Log.w(TAG, "Could not get EXIF orientation of image"); 1104 | } 1105 | break; 1106 | case URL: 1107 | InputStream inputStream = CacheManager.getInstance(context).get(source.hashCode()+""); 1108 | if(inputStream == null){ 1109 | InputStream is = getUrlResponse(source); 1110 | if(is != null){ 1111 | InputStream savedIs = CacheManager.getInstance(context).saveCache(source.hashCode()+"",is); 1112 | decoder = BitmapRegionDecoder.newInstance(savedIs, true); 1113 | }else{ 1114 | throw new IllegalArgumentException("the request image url can not attach!"); 1115 | } 1116 | }else { 1117 | decoder = BitmapRegionDecoder.newInstance(inputStream, true); 1118 | } 1119 | break; 1120 | } 1121 | return new int[] { decoder.getWidth(), decoder.getHeight(), exifOrientation }; 1122 | } 1123 | } 1124 | } catch (Exception e) { 1125 | Log.e(TAG, "Failed to initialise bitmap decoder", e); 1126 | } 1127 | return null; 1128 | } 1129 | 1130 | // request the url, and get the response 1131 | private InputStream getUrlResponse(String source) { 1132 | InputStream is = null; 1133 | DefaultHttpClient client = new DefaultHttpClient(); 1134 | HttpGet request = new HttpGet(source); 1135 | try { 1136 | is = client.execute(request).getEntity().getContent(); 1137 | } catch (IOException e) { 1138 | e.printStackTrace(); 1139 | } 1140 | return is; 1141 | } 1142 | 1143 | @Override 1144 | protected void onPostExecute(int[] xyo) { 1145 | if (viewRef != null && decoder != null) { 1146 | final SubsamplingScaleImageView subsamplingScaleImageView = viewRef.get(); 1147 | if (subsamplingScaleImageView != null && decoder != null && xyo != null && xyo.length == 3) { 1148 | subsamplingScaleImageView.onImageInited(decoder, xyo[0], xyo[1], xyo[2]); 1149 | if(subsamplingScaleImageView.getLongImageLoadingListener() != null){ 1150 | subsamplingScaleImageView.getLongImageLoadingListener().loadingComplete(); 1151 | } 1152 | }else{ 1153 | subsamplingScaleImageView.getLongImageLoadingListener().loadingFailed(); 1154 | } 1155 | } 1156 | } 1157 | } 1158 | 1159 | /** 1160 | * Async task used to load images without blocking the UI thread. 1161 | */ 1162 | private static class BitmapTileTask extends AsyncTask { 1163 | private final WeakReference viewRef; 1164 | private final WeakReference decoderRef; 1165 | private final WeakReference decoderLockRef; 1166 | private final WeakReference tileRef; 1167 | 1168 | public BitmapTileTask(SubsamplingScaleImageView view, BitmapRegionDecoder decoder, Object decoderLock, Tile tile) { 1169 | this.viewRef = new WeakReference(view); 1170 | this.decoderRef = new WeakReference(decoder); 1171 | this.decoderLockRef = new WeakReference(decoderLock); 1172 | this.tileRef = new WeakReference(tile); 1173 | tile.loading = true; 1174 | } 1175 | 1176 | @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) 1177 | @Override 1178 | protected Bitmap doInBackground(Void... params) { 1179 | try { 1180 | if (decoderRef != null && tileRef != null && viewRef != null) { 1181 | final BitmapRegionDecoder decoder = decoderRef.get(); 1182 | final Object decoderLock = decoderLockRef.get(); 1183 | final Tile tile = tileRef.get(); 1184 | final SubsamplingScaleImageView view = viewRef.get(); 1185 | if (decoder != null && decoderLock != null && tile != null && view != null && !decoder.isRecycled()) { 1186 | synchronized (decoderLock) { 1187 | BitmapFactory.Options options = new BitmapFactory.Options(); 1188 | options.inSampleSize = tile.sampleSize; 1189 | options.inPreferredConfig = Config.RGB_565; 1190 | options.inDither = true; 1191 | Bitmap bitmap = decoder.decodeRegion(view.fileSRect(tile.sRect), options); 1192 | int rotation = view.getRequiredRotation(); 1193 | if (rotation != 0) { 1194 | Matrix matrix = new Matrix(); 1195 | matrix.postRotate(rotation); 1196 | bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); 1197 | } 1198 | return bitmap; 1199 | } 1200 | } else if (tile != null) { 1201 | tile.loading = false; 1202 | } 1203 | } 1204 | } catch (Exception e) { 1205 | Log.e(TAG, "Failed to decode tile", e); 1206 | } 1207 | return null; 1208 | } 1209 | 1210 | @Override 1211 | protected void onPostExecute(Bitmap bitmap) { 1212 | if (viewRef != null && tileRef != null && bitmap != null) { 1213 | final SubsamplingScaleImageView subsamplingScaleImageView = viewRef.get(); 1214 | final Tile tile = tileRef.get(); 1215 | if (subsamplingScaleImageView != null && tile != null) { 1216 | tile.bitmap = bitmap; 1217 | tile.loading = false; 1218 | subsamplingScaleImageView.onTileLoaded(); 1219 | } 1220 | } 1221 | } 1222 | } 1223 | 1224 | private static class Tile { 1225 | 1226 | private Rect sRect; 1227 | private int sampleSize; 1228 | private Bitmap bitmap; 1229 | private boolean loading; 1230 | private boolean visible; 1231 | 1232 | } 1233 | 1234 | private static class Anim { 1235 | 1236 | private float scaleStart; // Scale at start of anim 1237 | private float scaleEnd; // Scale at end of anim (target) 1238 | private PointF sCenterStart; // Source center point at start 1239 | private PointF sCenterEnd; // Source center point at end, adjusted for pan limits 1240 | private PointF sCenterEndRequested; // Source center point that was requested, without adjustment 1241 | private PointF vFocusStart; // View point that was double tapped 1242 | private PointF vFocusEnd; // Where the view focal point should be moved to during the anim 1243 | private long duration = 500; // How long the anim takes 1244 | private boolean interruptible = true; // Whether the anim can be interrupted by a touch 1245 | private int easing = EASE_IN_OUT_QUAD; // Easing style 1246 | private long time = System.currentTimeMillis(); // Start time 1247 | 1248 | } 1249 | 1250 | private static class ScaleAndTranslate { 1251 | private ScaleAndTranslate(float scale, PointF translate) { 1252 | this.scale = scale; 1253 | this.translate = translate; 1254 | } 1255 | private float scale; 1256 | private PointF translate; 1257 | } 1258 | 1259 | /** 1260 | * Set scale, center and orientation from saved state. 1261 | */ 1262 | private void restoreState(ImageViewState state) { 1263 | if (state != null && state.getCenter() != null && VALID_ORIENTATIONS.contains(state.getOrientation())) { 1264 | this.orientation = state.getOrientation(); 1265 | this.pendingScale = state.getScale(); 1266 | this.sPendingCenter = state.getCenter(); 1267 | invalidate(); 1268 | } 1269 | } 1270 | 1271 | /** 1272 | * In SDK 14 and above, use canvas max bitmap width and height instead of the default 2048, to avoid redundant tiling. 1273 | */ 1274 | private Point getMaxBitmapDimensions(Canvas canvas) { 1275 | if (VERSION.SDK_INT >= 14) { 1276 | try { 1277 | int maxWidth = (Integer)Canvas.class.getMethod("getMaximumBitmapWidth").invoke(canvas); 1278 | int maxHeight = (Integer)Canvas.class.getMethod("getMaximumBitmapHeight").invoke(canvas); 1279 | return new Point(maxWidth, maxHeight); 1280 | } catch (Exception e) { 1281 | // Return default 1282 | } 1283 | } 1284 | return new Point(2048, 2048); 1285 | } 1286 | 1287 | /** 1288 | * Get source width taking rotation into account. 1289 | */ 1290 | private int sWidth() { 1291 | int rotation = getRequiredRotation(); 1292 | if (rotation == 90 || rotation == 270) { 1293 | return sHeight; 1294 | } else { 1295 | return sWidth; 1296 | } 1297 | } 1298 | 1299 | /** 1300 | * Get source height taking rotation into account. 1301 | */ 1302 | private int sHeight() { 1303 | int rotation = getRequiredRotation(); 1304 | if (rotation == 90 || rotation == 270) { 1305 | return sWidth; 1306 | } else { 1307 | return sHeight; 1308 | } 1309 | } 1310 | 1311 | /** 1312 | * Converts source rectangle from tile, which treats the image file as if it were in the correct orientation already, 1313 | * to the rectangle of the image that needs to be loaded. 1314 | */ 1315 | private Rect fileSRect(Rect sRect) { 1316 | if (getRequiredRotation() == 0) { 1317 | return sRect; 1318 | } else if (getRequiredRotation() == 90) { 1319 | return new Rect(sRect.top, sHeight - sRect.right, sRect.bottom, sHeight - sRect.left); 1320 | } else if (getRequiredRotation() == 180) { 1321 | return new Rect(sWidth - sRect.right, sHeight - sRect.bottom, sWidth - sRect.left, sHeight - sRect.top); 1322 | } else { 1323 | return new Rect(sWidth - sRect.bottom, sRect.left, sWidth - sRect.top, sRect.right); 1324 | } 1325 | } 1326 | 1327 | /** 1328 | * Determines the rotation to be applied to tiles, based on EXIF orientation or chosen setting. 1329 | */ 1330 | private int getRequiredRotation() { 1331 | if (orientation == ORIENTATION_USE_EXIF) { 1332 | return sOrientation; 1333 | } else { 1334 | return orientation; 1335 | } 1336 | } 1337 | 1338 | /** 1339 | * Pythagoras distance between two points. 1340 | */ 1341 | private float distance(float x0, float x1, float y0, float y1) { 1342 | float x = x0 - x1; 1343 | float y = y0 - y1; 1344 | return FloatMath.sqrt(x * x + y * y); 1345 | } 1346 | 1347 | /** 1348 | * Convert screen coordinate to source coordinate. 1349 | */ 1350 | public final PointF viewToSourceCoord(PointF vxy) { 1351 | return viewToSourceCoord(vxy.x, vxy.y); 1352 | } 1353 | 1354 | /** 1355 | * Convert screen coordinate to source coordinate. 1356 | */ 1357 | public final PointF viewToSourceCoord(float vx, float vy) { 1358 | if (vTranslate == null) { 1359 | return null; 1360 | } 1361 | float sx = (vx - vTranslate.x)/scale; 1362 | float sy = (vy - vTranslate.y)/scale; 1363 | return new PointF(sx, sy); 1364 | } 1365 | 1366 | /** 1367 | * Convert source coordinate to screen coordinate. 1368 | */ 1369 | public final PointF sourceToViewCoord(PointF sxy) { 1370 | return sourceToViewCoord(sxy.x, sxy.y); 1371 | } 1372 | 1373 | /** 1374 | * Convert source coordinate to screen coordinate. 1375 | */ 1376 | public final PointF sourceToViewCoord(float sx, float sy) { 1377 | if (vTranslate == null) { 1378 | return null; 1379 | } 1380 | float vx = (sx * scale) + vTranslate.x; 1381 | float vy = (sy * scale) + vTranslate.y; 1382 | return new PointF(vx, vy); 1383 | } 1384 | 1385 | /** 1386 | * Convert source rect to screen rect. 1387 | */ 1388 | private RectF sourceToViewRect(Rect sRect) { 1389 | return sourceToViewRect(convertRect(sRect)); 1390 | } 1391 | 1392 | /** 1393 | * Convert source rect to screen rect. 1394 | */ 1395 | private RectF sourceToViewRect(RectF sRect) { 1396 | PointF vLT = sourceToViewCoord(new PointF(sRect.left, sRect.top)); 1397 | PointF vRB = sourceToViewCoord(new PointF(sRect.right, sRect.bottom)); 1398 | return new RectF(vLT.x, vLT.y, vRB.x, vRB.y); 1399 | } 1400 | 1401 | /** 1402 | * Convert screen rect to source rect. 1403 | */ 1404 | private RectF viewToSourceRect(RectF vRect) { 1405 | PointF sLT = viewToSourceCoord(new PointF(vRect.left, vRect.top)); 1406 | PointF sRB = viewToSourceCoord(new PointF(vRect.right, vRect.bottom)); 1407 | return new RectF(sLT.x, sLT.y, sRB.x, sRB.y); 1408 | } 1409 | 1410 | /** 1411 | * Int to float rect conversion. 1412 | */ 1413 | private RectF convertRect(Rect rect) { 1414 | return new RectF(rect.left, rect.top, rect.right, rect.bottom); 1415 | } 1416 | 1417 | /** 1418 | * Float to int rect conversion. 1419 | */ 1420 | private Rect convertRect(RectF rect) { 1421 | return new Rect((int)rect.left, (int)rect.top, (int)rect.right, (int)rect.bottom); 1422 | } 1423 | 1424 | /** 1425 | * Get the translation required to place a given source coordinate at the center of the screen. Accepts the desired 1426 | * scale as an argument, so this is independent of current translate and scale. The result is fitted to bounds, putting 1427 | * the image point as near to the screen center as permitted. 1428 | */ 1429 | private PointF vTranslateForSCenter(PointF sCenter, float scale) { 1430 | PointF vTranslate = new PointF((getWidth()/2) - (sCenter.x * scale), (getHeight()/2) - (sCenter.y * scale)); 1431 | ScaleAndTranslate sat = new ScaleAndTranslate(scale, vTranslate); 1432 | fitToBounds(true, sat); 1433 | return vTranslate; 1434 | } 1435 | 1436 | /** 1437 | * Given a requested source center and scale, calculate what the actual center will have to be to keep the image in 1438 | * pan limits, keeping the requested center as near to the middle of the screen as allowed. 1439 | */ 1440 | private PointF limitedSCenter(PointF sCenter, float scale) { 1441 | PointF vTranslate = vTranslateForSCenter(sCenter, scale); 1442 | int mY = getHeight()/2; 1443 | float sx = ((getWidth()/2) - vTranslate.x)/scale; 1444 | float sy = ((getHeight()/2) - vTranslate.y)/scale; 1445 | return new PointF(sx, sy); 1446 | } 1447 | 1448 | /** 1449 | * Returns the minimum allowed scale. 1450 | */ 1451 | private float minScale() { 1452 | if (minimumScaleType == SCALE_TYPE_CENTER_INSIDE) { 1453 | return Math.min(getWidth() / (float) sWidth(), getHeight() / (float) sHeight()); 1454 | } else { 1455 | return Math.max(getWidth() / (float) sWidth(), getHeight() / (float) sHeight()); 1456 | } 1457 | } 1458 | 1459 | /** 1460 | * Adjust a requested scale to be within the allowed limits. 1461 | */ 1462 | private float limitedScale(float targetScale) { 1463 | targetScale = Math.max(minScale(), targetScale); 1464 | targetScale = Math.min(maxScale, targetScale); 1465 | return targetScale; 1466 | } 1467 | 1468 | /** 1469 | * Apply a selected type of easing. 1470 | * @param type Easing type, from static fields 1471 | * @param time Elapsed time 1472 | * @param from Start value 1473 | * @param change Target value 1474 | * @param duration Anm duration 1475 | * @return Current value 1476 | */ 1477 | private float ease(int type, long time, float from, float change, long duration) { 1478 | switch (type) { 1479 | case EASE_IN_OUT_QUAD: 1480 | return easeInOutQuad(time, from, change, duration); 1481 | case EASE_OUT_QUAD: 1482 | return easeOutQuad(time, from, change, duration); 1483 | default: 1484 | throw new IllegalStateException("Unexpected easing type: " + type); 1485 | } 1486 | } 1487 | 1488 | /** 1489 | * Quadratic easing for fling. With thanks to Robert Penner - http://gizma.com/easing/ 1490 | * @param time Elapsed time 1491 | * @param from Start value 1492 | * @param change Target value 1493 | * @param duration Anm duration 1494 | * @return Current value 1495 | */ 1496 | private float easeOutQuad(long time, float from, float change, long duration) { 1497 | float progress = (float)time/(float)duration; 1498 | return -change * progress*(progress-2) + from; 1499 | } 1500 | 1501 | /** 1502 | * Quadratic easing for scale and center animations. With thanks to Robert Penner - http://gizma.com/easing/ 1503 | * @param time Elapsed time 1504 | * @param from Start value 1505 | * @param change Target value 1506 | * @param duration Anm duration 1507 | * @return Current value 1508 | */ 1509 | private float easeInOutQuad(long time, float from, float change, long duration) { 1510 | float timeF = time/(duration/2f); 1511 | if (timeF < 1) { 1512 | return (change/2f * timeF * timeF) + from; 1513 | } else { 1514 | timeF--; 1515 | return (-change/2f) * (timeF * (timeF - 2) - 1) + from; 1516 | } 1517 | } 1518 | 1519 | /** 1520 | * Set the pan limiting style. See static fields. Normally {@link #PAN_LIMIT_INSIDE} is best, for image galleries. 1521 | */ 1522 | public final void setPanLimit(int panLimit) { 1523 | if (!VALID_PAN_LIMITS.contains(panLimit)) { 1524 | throw new IllegalArgumentException("Invalid pan limit: " + panLimit); 1525 | } 1526 | this.panLimit = panLimit; 1527 | if (isImageReady()) { 1528 | fitToBounds(true); 1529 | invalidate(); 1530 | } 1531 | } 1532 | 1533 | /** 1534 | * Set the minimum scale type. See static fields. Normally {@link #SCALE_TYPE_CENTER_INSIDE} is best, for image galleries. 1535 | */ 1536 | public final void setMinimumScaleType(int scaleType) { 1537 | if (!VALID_SCALE_TYPES.contains(scaleType)) { 1538 | throw new IllegalArgumentException("Invalid scale type: " + scaleType); 1539 | } 1540 | this.minimumScaleType = scaleType; 1541 | if (isImageReady()) { 1542 | fitToBounds(true); 1543 | invalidate(); 1544 | } 1545 | } 1546 | 1547 | /** 1548 | * Set the maximum scale allowed. A value of 1 means 1:1 pixels at maximum scale. You may wish to set this according 1549 | * to screen density - on a retina screen, 1:1 may still be too small. Consider using {@link #setMinimumDpi(int)}, 1550 | * which is density aware. 1551 | */ 1552 | public final void setMaxScale(float maxScale) { 1553 | this.maxScale = maxScale; 1554 | } 1555 | 1556 | /** 1557 | * Returns the maximum allowed scale. 1558 | */ 1559 | public float getMaxScale() { 1560 | return maxScale; 1561 | } 1562 | 1563 | /** 1564 | * This is a screen density aware alternative to {@link #setMaxScale(float)}; it allows you to express the maximum 1565 | * allowed scale in terms of the minimum pixel density. This avoids the problem of 1:1 scale still being 1566 | * too small on a high density screen. A sensible starting point is 160 - the default used by this view. 1567 | * @param dpi Source image pixel density at maximum zoom. 1568 | */ 1569 | public final void setMinimumDpi(int dpi) { 1570 | DisplayMetrics metrics = getResources().getDisplayMetrics(); 1571 | float averageDpi = (metrics.xdpi + metrics.ydpi)/2; 1572 | setMaxScale(averageDpi/dpi); 1573 | } 1574 | 1575 | /** 1576 | * Returns the minimum allowed scale. 1577 | */ 1578 | public final float getMinScale() { 1579 | return minScale(); 1580 | } 1581 | 1582 | /** 1583 | * By default, image tiles are at least as high resolution as the screen. For a retina screen this may not be 1584 | * necessary, and may increase the likelihood of an OutOfMemoryError. This method sets a DPI at which higher 1585 | * resolution tiles should be loaded. Using a lower number will on average use less memory but result in a lower 1586 | * quality image. 160-240dpi will usually be enough. 1587 | * @param minimumTileDpi Tile loading threshold. 1588 | */ 1589 | public void setMinimumTileDpi(int minimumTileDpi) { 1590 | DisplayMetrics metrics = getResources().getDisplayMetrics(); 1591 | float averageDpi = (metrics.xdpi + metrics.ydpi)/2; 1592 | this.minimumTileDpi = (int)Math.min(averageDpi, minimumTileDpi); 1593 | if (isImageReady()) { 1594 | reset(false); 1595 | invalidate(); 1596 | } 1597 | } 1598 | 1599 | /** 1600 | * Returns the source point at the center of the view. 1601 | */ 1602 | public final PointF getCenter() { 1603 | int mX = getWidth()/2; 1604 | int mY = getHeight()/2; 1605 | return viewToSourceCoord(mX, mY); 1606 | } 1607 | 1608 | /** 1609 | * Returns the current scale value. 1610 | */ 1611 | public final float getScale() { 1612 | return scale; 1613 | } 1614 | 1615 | /** 1616 | * Externally change the scale and translation of the source image. This may be used with getCenter() and getScale() 1617 | * to restore the scale and zoom after a screen rotate. 1618 | * @param scale New scale to set. 1619 | * @param sCenter New source image coordinate to center on the screen, subject to boundaries. 1620 | */ 1621 | public final void setScaleAndCenter(float scale, PointF sCenter) { 1622 | this.anim = null; 1623 | this.pendingScale = scale; 1624 | this.sPendingCenter = sCenter; 1625 | this.sRequestedCenter = sCenter; 1626 | invalidate(); 1627 | } 1628 | 1629 | /** 1630 | * Fully zoom out and return the image to the middle of the screen. This might be useful if you have a view pager 1631 | * and want images to be reset when the user has moved to another page. 1632 | */ 1633 | public final void resetScaleAndCenter() { 1634 | this.anim = null; 1635 | this.pendingScale = limitedScale(0); 1636 | if (isImageReady()) { 1637 | this.sPendingCenter = new PointF(sWidth()/2, sHeight()/2); 1638 | } else { 1639 | this.sPendingCenter = new PointF(0, 0); 1640 | } 1641 | invalidate(); 1642 | } 1643 | 1644 | /** 1645 | * Subclasses can override this method to be informed when the view is set up and ready for rendering, so they can 1646 | * skip their own rendering until the base layer (and its scale and translate) are known. 1647 | */ 1648 | protected void onImageReady() { 1649 | 1650 | } 1651 | 1652 | /** 1653 | * Call to find whether the view is initialised and ready for rendering tiles. 1654 | */ 1655 | public final boolean isImageReady() { 1656 | return readySent && vTranslate != null && tileMap != null && sWidth > 0 && sHeight > 0; 1657 | } 1658 | 1659 | /** 1660 | * Get source width, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSHeight()} 1661 | * for the apparent width. 1662 | */ 1663 | public final int getSWidth() { 1664 | return sWidth; 1665 | } 1666 | 1667 | /** 1668 | * Get source height, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSWidth()} 1669 | * for the apparent height. 1670 | */ 1671 | public final int getSHeight() { 1672 | return sHeight; 1673 | } 1674 | 1675 | /** 1676 | * Returns the orientation setting. This can return {@link #ORIENTATION_USE_EXIF}, in which case it doesn't tell you 1677 | * the applied orientation of the image. For that, use {@link #getAppliedOrientation()}. 1678 | */ 1679 | public final int getOrientation() { 1680 | return orientation; 1681 | } 1682 | 1683 | /** 1684 | * Returns the actual orientation of the image relative to the source file. This will be based on the source file's 1685 | * EXIF orientation if you're using ORIENTATION_USE_EXIF. Values are 0, 90, 180, 270. 1686 | */ 1687 | public final int getAppliedOrientation() { 1688 | return getRequiredRotation(); 1689 | } 1690 | 1691 | /** 1692 | * Get the current state of the view (scale, center, orientation) for restoration after rotate. Will return null if 1693 | * the view is not ready. 1694 | */ 1695 | public final ImageViewState getState() { 1696 | if (vTranslate != null && sWidth > 0 && sHeight > 0) { 1697 | return new ImageViewState(getScale(), getCenter(), getOrientation()); 1698 | } 1699 | return null; 1700 | } 1701 | 1702 | /** 1703 | * Returns true if zoom gesture detection is enabled. 1704 | */ 1705 | public final boolean isZoomEnabled() { 1706 | return zoomEnabled; 1707 | } 1708 | 1709 | /** 1710 | * Enable or disable zoom gesture detection. Disabling zoom locks the the current scale. 1711 | */ 1712 | public final void setZoomEnabled(boolean zoomEnabled) { 1713 | this.zoomEnabled = zoomEnabled; 1714 | } 1715 | 1716 | /** 1717 | * Returns true if pan gesture detection is enabled. 1718 | */ 1719 | public final boolean isPanEnabled() { 1720 | return panEnabled; 1721 | } 1722 | 1723 | /** 1724 | * Enable or disable pan gesture detection. Disabling pan causes the image to be centered. 1725 | */ 1726 | public final void setPanEnabled(boolean panEnabled) { 1727 | this.panEnabled = panEnabled; 1728 | if (!panEnabled && vTranslate != null) { 1729 | vTranslate.x = (getWidth()/2) - (scale * (sWidth()/2)); 1730 | vTranslate.y = (getHeight()/2) - (scale * (sHeight()/2)); 1731 | if (isImageReady()) { 1732 | refreshRequiredTiles(true); 1733 | invalidate(); 1734 | } 1735 | } 1736 | } 1737 | 1738 | /** 1739 | * Set the scale the image will zoom in to when double tapped. This also the scale point where a double tap is interpreted 1740 | * as a zoom out gesture - if the scale is greater than 90% of this value, a double tap zooms out. Avoid using values 1741 | * greater than the max zoom. 1742 | * @param doubleTapZoomScale New value for double tap gesture zoom scale. 1743 | */ 1744 | public final void setDoubleTapZoomScale(float doubleTapZoomScale) { 1745 | this.doubleTapZoomScale = doubleTapZoomScale; 1746 | } 1747 | 1748 | /** 1749 | * A density aware alternative to {@link #setDoubleTapZoomScale(float)}; this allows you to express the scale the 1750 | * image will zoom in to when double tapped in terms of the image pixel density. Values lower than the max scale will 1751 | * be ignored. A sensible starting point is 160 - the default used by this view. 1752 | * @param dpi New value for double tap gesture zoom scale. 1753 | */ 1754 | public final void setDoubleTapZoomDpi(int dpi) { 1755 | DisplayMetrics metrics = getResources().getDisplayMetrics(); 1756 | float averageDpi = (metrics.xdpi + metrics.ydpi)/2; 1757 | setDoubleTapZoomScale(averageDpi/dpi); 1758 | } 1759 | 1760 | /** 1761 | * Set the type of zoom animation to be used for double taps. See static fields. 1762 | * @param doubleTapZoomStyle New value for zoom style. 1763 | */ 1764 | public final void setDoubleTapZoomStyle(int doubleTapZoomStyle) { 1765 | if (!VALID_ZOOM_STYLES.contains(doubleTapZoomStyle)) { 1766 | throw new IllegalArgumentException("Invalid zoom style: " + doubleTapZoomStyle); 1767 | } 1768 | this.doubleTapZoomStyle = doubleTapZoomStyle; 1769 | } 1770 | 1771 | /** 1772 | * Enables visual debugging, showing tile boundaries and sizes. 1773 | */ 1774 | public final void setDebug(boolean debug) { 1775 | this.debug = debug; 1776 | } 1777 | 1778 | /** 1779 | * Creates a panning animation builder, that when started will animate the image to place the given coordinates of 1780 | * the image in the center of the screen. If doing this would move the image beyond the edges of the screen, the 1781 | * image is instead animated to move the center point as near to the center of the screen as is allowed - it's 1782 | * guaranteed to be on screen. 1783 | * @param sCenter Target center point 1784 | * @return {@link xiaofan.llongimageview.view.SubsamplingScaleImageView.AnimationBuilder} instance. Call {@link xiaofan.llongimageview.view.SubsamplingScaleImageView.AnimationBuilder#start()} to start the anim. 1785 | */ 1786 | public AnimationBuilder animateCenter(PointF sCenter) { 1787 | if (!isImageReady()) { 1788 | return null; 1789 | } 1790 | return new AnimationBuilder(sCenter); 1791 | } 1792 | 1793 | /** 1794 | * Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image 1795 | * beyond the panning limits, the image is automatically panned during the animation. 1796 | * @param scale Target scale. 1797 | * @return {@link xiaofan.llongimageview.view.SubsamplingScaleImageView.AnimationBuilder} instance. Call {@link xiaofan.llongimageview.view.SubsamplingScaleImageView.AnimationBuilder} to start the anim. 1798 | */ 1799 | public AnimationBuilder animateScale(float scale) { 1800 | if (!isImageReady()) { 1801 | return null; 1802 | } 1803 | return new AnimationBuilder(scale); 1804 | } 1805 | 1806 | /** 1807 | * Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image 1808 | * beyond the panning limits, the image is automatically panned during the animation. 1809 | * @param scale Target scale. 1810 | * @return {@link xiaofan.llongimageview.view.SubsamplingScaleImageView.AnimationBuilder} instance. Call {@link xiaofan.llongimageview.view.SubsamplingScaleImageView.AnimationBuilder#start()} to start the anim. 1811 | */ 1812 | public AnimationBuilder animateScaleAndCenter(float scale, PointF sCenter) { 1813 | if (!isImageReady()) { 1814 | return null; 1815 | } 1816 | return new AnimationBuilder(scale, sCenter); 1817 | } 1818 | 1819 | public void setFitScreen(boolean isFitScreen) { 1820 | this.isFitScreen = isFitScreen; 1821 | } 1822 | 1823 | /** 1824 | * Builder class used to set additional options for a scale animation. Create an instance using {@link #animateScale(float)}, 1825 | * then set your options and call {@link #start()}. 1826 | */ 1827 | public final class AnimationBuilder { 1828 | 1829 | private final float targetScale; 1830 | private final PointF targetSCenter; 1831 | private final PointF vFocus; 1832 | private long duration = 500; 1833 | private int easing = EASE_IN_OUT_QUAD; 1834 | private boolean interruptible = true; 1835 | private boolean panLimited = true; 1836 | 1837 | private AnimationBuilder(PointF sCenter) { 1838 | this.targetScale = scale; 1839 | this.targetSCenter = sCenter; 1840 | this.vFocus = null; 1841 | } 1842 | 1843 | private AnimationBuilder(float scale) { 1844 | this.targetScale = scale; 1845 | this.targetSCenter = getCenter(); 1846 | this.vFocus = null; 1847 | } 1848 | 1849 | private AnimationBuilder(float scale, PointF sCenter) { 1850 | this.targetScale = scale; 1851 | this.targetSCenter = sCenter; 1852 | this.vFocus = null; 1853 | } 1854 | 1855 | private AnimationBuilder(float scale, PointF sCenter, PointF vFocus) { 1856 | this.targetScale = scale; 1857 | this.targetSCenter = sCenter; 1858 | this.vFocus = vFocus; 1859 | } 1860 | 1861 | /** 1862 | * Desired duration of the anim in milliseconds. Default is 500. 1863 | * @param duration duration in milliseconds. 1864 | * @return this builder for method chaining. 1865 | */ 1866 | public AnimationBuilder withDuration(long duration) { 1867 | this.duration = duration; 1868 | return this; 1869 | } 1870 | 1871 | /** 1872 | * Whether the animation can be interrupted with a touch. Default is true. 1873 | * @param interruptible interruptible flag. 1874 | * @return this builder for method chaining. 1875 | */ 1876 | public AnimationBuilder withInterruptible(boolean interruptible) { 1877 | this.interruptible = interruptible; 1878 | return this; 1879 | } 1880 | 1881 | /** 1882 | * Set the easing style. See static fields. {@link #EASE_IN_OUT_QUAD} is recommended, and the default. 1883 | * @param easing easing style. 1884 | * @return this builder for method chaining. 1885 | */ 1886 | public AnimationBuilder withEasing(int easing) { 1887 | if (!VALID_EASING_STYLES.contains(easing)) { 1888 | throw new IllegalArgumentException("Unknown easing type: " + easing); 1889 | } 1890 | this.easing = easing; 1891 | return this; 1892 | } 1893 | 1894 | /** 1895 | * Only for internal use. When set to true, the animation proceeds towards the actual end point - the nearest 1896 | * point to the center allowed by pan limits. When false, animation is in the direction of the requested end 1897 | * point and is stopped when the limit for each axis is reached. The latter behaviour is used for flings but 1898 | * nothing else. 1899 | */ 1900 | private AnimationBuilder withPanLimited(boolean panLimited) { 1901 | this.panLimited = panLimited; 1902 | return this; 1903 | } 1904 | 1905 | /** 1906 | * Starts the animation. 1907 | */ 1908 | public void start() { 1909 | float targetScale = limitedScale(this.targetScale); 1910 | PointF targetSCenter = panLimited ? limitedSCenter(this.targetSCenter, targetScale) : this.targetSCenter; 1911 | anim = new Anim(); 1912 | anim.scaleStart = scale; 1913 | anim.scaleEnd = targetScale; 1914 | anim.time = System.currentTimeMillis(); 1915 | anim.sCenterEndRequested = targetSCenter; 1916 | anim.sCenterStart = getCenter(); 1917 | anim.sCenterEnd = targetSCenter; 1918 | anim.vFocusStart = sourceToViewCoord(targetSCenter); 1919 | anim.vFocusEnd = new PointF( 1920 | getWidth()/2, 1921 | getHeight()/2 1922 | ); 1923 | anim.duration = duration; 1924 | anim.interruptible = interruptible; 1925 | anim.easing = easing; 1926 | anim.time = System.currentTimeMillis(); 1927 | 1928 | if (vFocus != null) { 1929 | // Calculate where translation will be at the end of the anim 1930 | float vTranslateXEnd = vFocus.x - (targetScale * anim.sCenterStart.x); 1931 | float vTranslateYEnd = vFocus.y - (targetScale * anim.sCenterStart.y); 1932 | ScaleAndTranslate satEnd = new ScaleAndTranslate(targetScale, new PointF(vTranslateXEnd, vTranslateYEnd)); 1933 | // Fit the end translation into bounds 1934 | fitToBounds(true, satEnd); 1935 | // Adjust the position of the focus point at end so image will be in bounds 1936 | anim.vFocusEnd = new PointF( 1937 | vFocus.x + (satEnd.translate.x - vTranslateXEnd), 1938 | vFocus.y + (satEnd.translate.y - vTranslateYEnd) 1939 | ); 1940 | } 1941 | 1942 | invalidate(); 1943 | } 1944 | 1945 | } 1946 | } 1947 | -------------------------------------------------------------------------------- /app/src/main/java/xiaofan/llongimageview/view/Utils.java: -------------------------------------------------------------------------------- 1 | package xiaofan.llongimageview.view; 2 | 3 | import android.content.Context; 4 | import android.os.Build; 5 | import android.os.Environment; 6 | 7 | import java.io.File; 8 | 9 | /** 10 | * Created by zhaoyu on 2014/9/26. 11 | */ 12 | public class Utils { 13 | 14 | public static File getDiskCacheDir(Context context, String uniqueName) { 15 | 16 | // Check if media is mounted or storage is built-in, if so, try and use external cache dir 17 | // otherwise use internal cache dir 18 | final String cachePath = 19 | Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED || 20 | !Utils.isExternalStorageRemovable() ? 21 | Utils.getExternalCacheDir(context).getPath() : 22 | context.getCacheDir().getPath(); 23 | 24 | return new File(cachePath + File.separator + uniqueName); 25 | } 26 | 27 | /** 28 | * Check if external storage is built-in or removable. 29 | * 30 | * @return True if external storage is removable (like an SD card), false 31 | * otherwise. 32 | */ 33 | public static boolean isExternalStorageRemovable() { 34 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { 35 | return Environment.isExternalStorageRemovable(); 36 | } 37 | return true; 38 | } 39 | 40 | /** 41 | * Get the external app cache directory. 42 | * 43 | * @param context The context to use 44 | * @return The external cache dir 45 | */ 46 | public static File getExternalCacheDir(Context context) { 47 | if (hasExternalCacheDir()) { 48 | return context.getExternalCacheDir(); 49 | } 50 | 51 | // Before Froyo we need to construct the external cache dir ourselves 52 | final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/"; 53 | return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir); 54 | } 55 | 56 | /** 57 | * Check if OS version has built-in external cache dir method. 58 | * 59 | * @return 60 | */ 61 | public static boolean hasExternalCacheDir() { 62 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; 63 | } 64 | 65 | 66 | 67 | } 68 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaofans/LLongImageView/3106f6791dc8a380428462564a242dc4afe07d77/app/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaofans/LLongImageView/3106f6791dc8a380428462564a242dc4afe07d77/app/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaofans/LLongImageView/3106f6791dc8a380428462564a242dc4afe07d77/app/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaofans/LLongImageView/3106f6791dc8a380428462564a242dc4afe07d77/app/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_my.xml: -------------------------------------------------------------------------------- 1 | 9 | 10 | 16 | 20 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /app/src/main/res/menu/my.xml: -------------------------------------------------------------------------------- 1 | 5 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | LLongImageView 5 | Hello world! 6 | Settings 7 | 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:0.12.2' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaofans/LLongImageView/3106f6791dc8a380428462564a242dc4afe07d77/demo.gif -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Settings specified in this file will override any Gradle settings 5 | # configured through the IDE. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaofans/LLongImageView/3106f6791dc8a380428462564a242dc4afe07d77/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Apr 10 15:27:10 PDT 2013 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=http\://services.gradle.org/distributions/gradle-1.12-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | --------------------------------------------------------------------------------