7 |
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 | 
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 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
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