Repository: davemorrissey/subsampling-scale-image-view
Branch: master
Commit: 173e421fdbfa
Files: 110
Total size: 1.0 MB
Directory structure:
gitextract_4u22zbc_/
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── build.gradle
├── docs/
│ ├── issue_template.md
│ └── javadoc/
│ ├── allclasses-frame.html
│ ├── allclasses-noframe.html
│ ├── com/
│ │ └── davemorrissey/
│ │ └── labs/
│ │ └── subscaleview/
│ │ ├── ImageSource.html
│ │ ├── ImageViewState.html
│ │ ├── SubsamplingScaleImageView.AnimationBuilder.html
│ │ ├── SubsamplingScaleImageView.DefaultOnAnimationEventListener.html
│ │ ├── SubsamplingScaleImageView.DefaultOnImageEventListener.html
│ │ ├── SubsamplingScaleImageView.DefaultOnStateChangedListener.html
│ │ ├── SubsamplingScaleImageView.OnAnimationEventListener.html
│ │ ├── SubsamplingScaleImageView.OnImageEventListener.html
│ │ ├── SubsamplingScaleImageView.OnStateChangedListener.html
│ │ ├── SubsamplingScaleImageView.html
│ │ ├── decoder/
│ │ │ ├── CompatDecoderFactory.html
│ │ │ ├── DecoderFactory.html
│ │ │ ├── ImageDecoder.html
│ │ │ ├── ImageRegionDecoder.html
│ │ │ ├── SkiaImageDecoder.html
│ │ │ ├── SkiaImageRegionDecoder.html
│ │ │ ├── SkiaPooledImageRegionDecoder.html
│ │ │ ├── package-frame.html
│ │ │ ├── package-summary.html
│ │ │ └── package-tree.html
│ │ ├── package-frame.html
│ │ ├── package-summary.html
│ │ └── package-tree.html
│ ├── constant-values.html
│ ├── deprecated-list.html
│ ├── help-doc.html
│ ├── index-all.html
│ ├── index.html
│ ├── overview-frame.html
│ ├── overview-summary.html
│ ├── overview-tree.html
│ ├── package-list
│ ├── script.js
│ ├── serialized-form.html
│ └── stylesheet.css
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── library/
│ ├── build.gradle
│ ├── proguard-rules.txt
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ ├── java/
│ │ └── com/
│ │ └── davemorrissey/
│ │ └── labs/
│ │ └── subscaleview/
│ │ ├── ImageSource.java
│ │ ├── ImageViewState.java
│ │ ├── SubsamplingScaleImageView.java
│ │ └── decoder/
│ │ ├── CompatDecoderFactory.java
│ │ ├── DecoderFactory.java
│ │ ├── ImageDecoder.java
│ │ ├── ImageRegionDecoder.java
│ │ ├── SkiaImageDecoder.java
│ │ ├── SkiaImageRegionDecoder.java
│ │ └── SkiaPooledImageRegionDecoder.java
│ └── res/
│ └── values/
│ └── attrs.xml
├── release.gradle
├── sample/
│ ├── build.gradle
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ ├── java/
│ │ └── com/
│ │ └── davemorrissey/
│ │ └── labs/
│ │ └── subscaleview/
│ │ └── test/
│ │ ├── AbstractFragmentsActivity.java
│ │ ├── AbstractPagesActivity.java
│ │ ├── MainActivity.java
│ │ ├── Page.java
│ │ ├── animation/
│ │ │ └── AnimationActivity.java
│ │ ├── basicfeatures/
│ │ │ └── BasicFeaturesActivity.java
│ │ ├── configuration/
│ │ │ └── ConfigurationActivity.java
│ │ ├── eventhandling/
│ │ │ └── EventHandlingActivity.java
│ │ ├── eventhandlingadvanced/
│ │ │ └── AdvancedEventHandlingActivity.java
│ │ ├── extension/
│ │ │ ├── ExtensionActivity.java
│ │ │ ├── ExtensionCircleFragment.java
│ │ │ ├── ExtensionFreehandFragment.java
│ │ │ ├── ExtensionPinFragment.java
│ │ │ └── views/
│ │ │ ├── CircleView.java
│ │ │ ├── FreehandView.java
│ │ │ └── PinView.java
│ │ ├── imagedisplay/
│ │ │ ├── ImageDisplayActivity.java
│ │ │ ├── ImageDisplayLargeFragment.java
│ │ │ ├── ImageDisplayRegionFragment.java
│ │ │ └── ImageDisplayRotateFragment.java
│ │ └── viewpager/
│ │ ├── VerticalViewPager.java
│ │ ├── ViewPagerActivity.java
│ │ └── ViewPagerFragment.java
│ └── res/
│ ├── drawable-nodpi/
│ │ ├── button_standout_inactive.xml
│ │ ├── button_standout_pressed.xml
│ │ ├── button_transparent_pressed.xml
│ │ ├── buttonstate_standout.xml
│ │ ├── buttonstate_transparent.xml
│ │ └── transparent.xml
│ ├── layout/
│ │ ├── animation_activity.xml
│ │ ├── extension_circle_fragment.xml
│ │ ├── extension_freehand_fragment.xml
│ │ ├── extension_pin_fragment.xml
│ │ ├── fragments_activity.xml
│ │ ├── imagedisplay_large_fragment.xml
│ │ ├── imagedisplay_region_fragment.xml
│ │ ├── imagedisplay_rotate_fragment.xml
│ │ ├── main.xml
│ │ ├── pages_activity.xml
│ │ ├── view_pager.xml
│ │ └── view_pager_page.xml
│ └── values/
│ ├── colors.xml
│ ├── strings.xml
│ └── style.xml
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Android Studio generated folders
.navigation/
captures/
.externalNativeBuild
# IntelliJ project files
*.iml
.idea/
# Misc
.DS_Store
================================================
FILE: CONTRIBUTING.md
================================================
Before raising a new issue, please check the following places for an answer to your question!
* Read through [the wiki](https://github.com/davemorrissey/subsampling-scale-image-view/wiki) for a comprehensive guide to using the view.
* Search through [open and closed issues](https://github.com/davemorrissey/subsampling-scale-image-view/issues?utf8=%E2%9C%93&q=is%3Aissue)
* Check examples in [the sample project](https://github.com/davemorrissey/subsampling-scale-image-view/tree/master/sample/src/com/davemorrissey/labs/subscaleview/sample) - most common uses are covered.
* See if there's an answer to your question on [StackOverflow](http://stackoverflow.com/).
If you get stuck adding the view in your project or need help extending it for your requirements, please consider asking for help on StackOverflow instead of raising an issue. This issue tracker is intended for reporting bugs and raising feature requests.
Thanks for reading!
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
Subsampling Scale Image View
===========================
A custom image view for Android, designed for photo galleries and displaying huge images (e.g. maps and building plans) without `OutOfMemoryError`s. Includes pinch to zoom, panning, rotation and animation support, and allows easy extension so you can add your own overlays and touch event detection.
The view optionally uses subsampling and tiles to support very large images - a low resolution base layer is loaded and as you zoom in, it is overlaid with smaller high resolution tiles for the visible area. This avoids holding too much data in memory. It's ideal for displaying large images while allowing you to zoom in to the high resolution details. You can disable tiling for smaller images and when displaying a bitmap object. There are some advantages and disadvantages to disabling tiling so to decide which is best, see [the wiki](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/02.-Displaying-images).
#### Guides
* [Releases & downloads](https://github.com/davemorrissey/subsampling-scale-image-view/releases)
* [Installation and setup](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/01.-Setup)
* [Image display notes & limitations](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/02.-Displaying-images)
* [Using preview images](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/03.-Preview-images)
* [Handling orientation changes](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/05.-Orientation-changes)
* [Advanced configuration](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/07.-Configuration)
* [Event handling](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/09.-Events)
* [Animation](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/08.-Animation)
* [Extension](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/10.-Extension)
* [Reference (JavaDocs)](http://davemorrissey.github.io/subsampling-scale-image-view/javadoc/)
#### Migration guides
Versions 3.9.0, 3.8.0 and 3.0.0 contain breaking changes. Migration instructions can be found [in the wiki](https://github.com/davemorrissey/subsampling-scale-image-view/wiki/X.--Migration-guides).
#### Download the sample app
[](https://play.google.com/store/apps/details?id=com.davemorrissey.labs.subscaleview.sample)
[Kotlin Sample App on GitHub](https://github.com/davemorrissey/ssiv-kotlin-sample)
#### Demo

## Features
#### Image display
* Display images from assets, resources, the file system or bitmaps
* Automatically rotate images from the file system (e.g. the camera or gallery) according to EXIF
* Manually rotate images in 90° increments
* Display a region of the source image
* Use a preview image while large images load
* Swap images at runtime
* Use a custom bitmap decoder
*With tiling enabled:*
* Display huge images, larger than can be loaded into memory
* Show high resolution detail on zooming in
* Tested up to 20,000x20,000px, though larger images are slower
#### Gesture detection
* One finger pan
* Two finger pinch to zoom
* Quick scale (one finger zoom)
* Pan while zooming
* Seamless switch between pan and zoom
* Fling momentum after panning
* Double tap to zoom in and out
* Options to disable pan and/or zoom gestures
#### Animation
* Public methods for animating the scale and center
* Customisable duration and easing
* Optional uninterruptible animations
#### Overridable event detection
* Supports `OnClickListener` and `OnLongClickListener`
* Supports interception of events using `GestureDetector` and `OnTouchListener`
* Extend to add your own gestures
#### Easy integration
* Use within a `ViewPager` to create a photo gallery
* Easily restore scale, center and orientation after screen rotation
* Can be extended to add overlay graphics that move and scale with the image
* Handles view resizing and `wrap_content` layout
## Quick start
**1)** Add this library as a dependency in your app's build.gradle file.
```gradle
dependencies {
implementation 'com.davemorrissey.labs:subsampling-scale-image-view:3.10.0'
}
```
If your project uses AndroidX, change the artifact name as follows:
```gradle
dependencies {
implementation 'com.davemorrissey.labs:subsampling-scale-image-view-androidx:3.10.0'
}
```
**2)** Add the view to your layout XML.
```xml
```
**3a)** Now, in your fragment or activity, set the image resource, asset name or file path.
```java
SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)findViewById(id.imageView);
imageView.setImage(ImageSource.resource(R.drawable.monkey));
// ... or ...
imageView.setImage(ImageSource.asset("map.png"))
// ... or ...
imageView.setImage(ImageSource.uri("/sdcard/DCIM/DSCM00123.JPG"));
```
**3b)** Or, if you have a `Bitmap` object in memory, load it into the view. This is unsuitable for large images because it bypasses subsampling - you may get an `OutOfMemoryError`.
```java
SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)findViewById(id.imageView);
imageView.setImage(ImageSource.bitmap(bitmap));
```
## Photo credits
* San Martino by Luca Bravo, via [unsplash.com](https://unsplash.com/photos/lWAOc0UuJ-A)
* Swiss Road by Ludovic Fremondiere, via [unsplash.com](https://unsplash.com/photos/3XN-BNRDUyY)
## About
Copyright 2018 David Morrissey, and licensed under the Apache License, Version 2.0. No attribution is necessary but it's very much appreciated. Star this project if you like it!
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
allprojects {
repositories {
mavenCentral()
jcenter()
google()
}
}
buildscript {
repositories {
mavenCentral()
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.1'
}
}
================================================
FILE: docs/issue_template.md
================================================
*Please provide as much of the following information as possible. Please do not raise issues to ask for help developing your app.*
### Expected behaviour
### Actual behaviour
### Steps to reproduce
(Include your setup code, and where relevant, your layout XML)
### Affected devices
(Specific devices, screen densities, SDK versions)
### Affected images
(Attach images you have problems with)
================================================
FILE: docs/javadoc/allclasses-frame.html
================================================
Helper class used to set the source and additional attributes from a variety of sources. Supports
use of a bitmap, asset, resource, external file or any other URI.
When you are using a preview image, you must set the dimensions of the full size image on the
ImageSource object for the full size image using the dimensions(int, int) method.
Provide a loaded and cached bitmap for display. This bitmap will not be recycled when it is no
longer needed. Use this method if you loaded the bitmap with an image loader such as Picasso
or Volley.
Enable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap.,
and tiling cannot be disabled when displaying a region of the source image.
Disable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap,
and tiling cannot be disabled when displaying a region of the source image.
Enable or disable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap,
and tiling cannot be disabled when displaying a region of the source image.
Declare the dimensions of the image. This is only required for a full size image, when you are specifying a URI
and also a preview image. When displaying a bitmap object, or not using a preview, you do not need to declare
the image dimensions. Note if the declared dimensions are found to be incorrect, the view will reset.
Called when the dimensions of the image and view are known, and either a preview image,
the full size image, or base layer tiles are loaded. This indicates the scale and translate
are known and the next draw will display an image. This event can be used to hide a loading
graphic, or inform a subclass that it is safe to draw overlays.
Called when the full size image is ready. When using tiling, this means the lowest resolution
base layer of tiles are loaded, and when tiling is disabled, the image bitmap is loaded.
This event could be used as a trigger to enable gestures if you wanted interaction disabled
while only a preview is displayed, otherwise for most cases SubsamplingScaleImageView.OnImageEventListener.onReady() is the best
event to listen to.
Called when a preview image could not be loaded. This method cannot be relied upon; certain
encoding types of supported image formats can result in corrupt or blank images being loaded
and displayed with no detectable error. The view will continue to load the full size image.
Indicates an error initiliasing the decoder when using a tiling, or when loading the full
size bitmap when tiling is disabled. This method cannot be relied upon; certain encoding
types of supported image formats can result in corrupt or blank images being loaded and
displayed with no detectable error.
Called when an image tile could not be loaded. This method cannot be relied upon; certain
encoding types of supported image formats can result in corrupt or blank images being loaded
and displayed with no detectable error. Most cases where an unsupported file is used will
result in an error caught by SubsamplingScaleImageView.OnImageEventListener.onImageLoadError(Exception).
Called when a bitmap set using ImageSource.cachedBitmap is no longer being used by the View.
This is useful if you wish to manage the bitmap after the preview is shown
public static interface SubsamplingScaleImageView.OnAnimationEventListener
An event listener for animations, allows events to be triggered when an animation completes,
is aborted by another animation starting, or is aborted by a touch event. Note that none of
these events are triggered if the activity is paused, the image is swapped, or in other cases
where the view's internal state gets wiped or draw events stop.
Called when the dimensions of the image and view are known, and either a preview image,
the full size image, or base layer tiles are loaded. This indicates the scale and translate
are known and the next draw will display an image. This event can be used to hide a loading
graphic, or inform a subclass that it is safe to draw overlays.
onImageLoaded
void onImageLoaded()
Called when the full size image is ready. When using tiling, this means the lowest resolution
base layer of tiles are loaded, and when tiling is disabled, the image bitmap is loaded.
This event could be used as a trigger to enable gestures if you wanted interaction disabled
while only a preview is displayed, otherwise for most cases onReady() is the best
event to listen to.
Called when a preview image could not be loaded. This method cannot be relied upon; certain
encoding types of supported image formats can result in corrupt or blank images being loaded
and displayed with no detectable error. The view will continue to load the full size image.
Parameters:
e - The exception thrown. This error is logged by the view.
Indicates an error initiliasing the decoder when using a tiling, or when loading the full
size bitmap when tiling is disabled. This method cannot be relied upon; certain encoding
types of supported image formats can result in corrupt or blank images being loaded and
displayed with no detectable error.
Parameters:
e - The exception thrown. This error is also logged by the view.
Called when an image tile could not be loaded. This method cannot be relied upon; certain
encoding types of supported image formats can result in corrupt or blank images being loaded
and displayed with no detectable error. Most cases where an unsupported file is used will
result in an error caught by onImageLoadError(Exception).
Parameters:
e - The exception thrown. This error is logged by the view.
onPreviewReleased
void onPreviewReleased()
Called when a bitmap set using ImageSource.cachedBitmap is no longer being used by the View.
This is useful if you wish to manage the bitmap after the preview is shown
public static interface SubsamplingScaleImageView.OnStateChangedListener
An event listener, allowing activities to be notified of pan and zoom events. Initialisation
and calls made by your code do not trigger events; touch events and animations do. Methods in
this listener will be called on the UI thread and may be called very frequently - your
implementation should return quickly.
public class SubsamplingScaleImageView
extends View
Displays an image subsampled as necessary to avoid loading too much image data into memory. After zooming in,
a set of image tiles subsampled at higher resolution are loaded and displayed over the base layer. During pan and
zoom, tiles off screen or higher/lower resolution than required are discarded from memory.
Tiles are no larger than the max supported bitmap size, so with large images tiling may be used even when zoomed out.
v prefixes - coordinates, translations and distances measured in screen (view) pixels
s prefixes - coordinates, translations and distances measured in rotated and cropped source image pixels (scaled)
f prefixes - coordinates, translations and distances measured in original unrotated, uncropped source file pixels
An event listener for animations, allows events to be triggered when an animation completes,
is aborted by another animation starting, or is aborted by a touch event.
A density aware alternative to setDoubleTapZoomScale(float); this allows you to express the scale the
image will zoom in to when double tapped in terms of the image pixel density.
Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be
displayed until the full size image is loaded, starting with a given orientation setting, scale and center.
This is a screen density aware alternative to setMinScale(float); it allows you to express the minimum
allowed scale in terms of the maximum pixel density.
This is a screen density aware alternative to setMaxScale(float); it allows you to express the maximum
allowed scale in terms of the minimum pixel density.
Converts a rectangle within the view to the corresponding rectangle from the source file, taking
into account the current scale, translation, orientation and clipped region.
Find the area of the source file that is currently visible on screen, taking into account the
current scale, translation, orientation and clipped region.
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.
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.
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.
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.
Scale the image so that both dimensions of the image will be equal to or less than the maxScale and equal to or larger than minScale. The image is then centered in the view.
public static Bitmap.Config getPreferredBitmapConfig()
Get the current preferred configuration for decoding bitmaps. ImageDecoder and ImageRegionDecoder
instances can read this and use it when decoding images.
Returns:
the preferred bitmap configuration, or null if none has been set.
setPreferredBitmapConfig
public static void setPreferredBitmapConfig(Bitmap.Config preferredBitmapConfig)
Set a global preferred bitmap config shared by all view instances and applied to new instances
initialised after the call is made. This is a hint only; the bundled ImageDecoder and
ImageRegionDecoder classes all respect this (except when they were constructed with
an instance-specific config) but custom decoder classes will not.
Parameters:
preferredBitmapConfig - the bitmap configuration to be used by future instances of the view. Pass null to restore the default.
setOrientation
public final void setOrientation(int orientation)
Sets the image orientation. It's best to call this before setting the image file or asset, because it may waste
loading of tiles. However, this can be freely called at any time.
Parameters:
orientation - orientation to be set. See ORIENTATION_ static fields for valid values.
Set the image source from a bitmap, resource, asset, file or other URI, starting with a given orientation
setting, scale and center. This is the best method to use when you want scale and center to be restored
after screen orientation change; it avoids any redundant loading of tiles in the wrong orientation.
Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be
displayed until the full size image is loaded.
You must declare the dimensions of the full size image by calling ImageSource.dimensions(int, int)
on the imageSource object. The preview source will be ignored if you don't provide dimensions,
and if you provide a bitmap for the full size image.
Parameters:
imageSource - Image source. Dimensions must be declared.
previewSource - Optional source for a preview image to be displayed and allow interaction while the full size image loads.
Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be
displayed until the full size image is loaded, starting with a given orientation setting, scale and center.
This is the best method to use when you want scale and center to be restored after screen orientation change;
it avoids any redundant loading of tiles in the wrong orientation.
You must declare the dimensions of the full size image by calling ImageSource.dimensions(int, int)
on the imageSource object. The preview source will be ignored if you don't provide dimensions,
and if you provide a bitmap for the full size image.
Parameters:
imageSource - Image source. Dimensions must be declared.
previewSource - Optional source for a preview image to be displayed and allow interaction while the full size image loads.
state - State to be restored. Nullable.
onSizeChanged
protected void onSizeChanged(int w,
int h,
int oldw,
int oldh)
On resize, preserve center and scale. Various behaviours are possible, override this method to use another.
protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec)
Measures the width and height of the view, preserving the aspect ratio of the image displayed if wrap_content is
used. The image will scale within this box, not resizing the view as it is zoomed.
Draw method should not be called until the view has dimensions so the first calls are used as triggers to calculate
the scaling and tiling required. Once the view is setup, tiles are displayed as they are loaded.
By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing TILE_SIZE_AUTO will re-enable the default behaviour.
Parameters:
maxPixels - Maximum tile size X and Y in pixels.
setMaxTileSize
public void setMaxTileSize(int maxPixelsX,
int maxPixelsY)
By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing TILE_SIZE_AUTO will re-enable the default behaviour.
Parameters:
maxPixelsX - Maximum tile width.
maxPixelsY - Maximum tile height.
recycle
public void recycle()
Releases all resources the view is using and resets the state, nulling any fields that use significant memory.
After you have called this method, the view can be re-used by setting a new image. Settings are remembered
but state (scale and center) is forgotten. You can restore these yourself if required.
viewToFileRect
public void viewToFileRect(Rect vRect,
Rect fRect)
Converts a rectangle within the view to the corresponding rectangle from the source file, taking
into account the current scale, translation, orientation and clipped region. This can be used
to decode a bitmap from the source file.
This method will only work when the image has fully initialised, after isReady() returns
true. It is not guaranteed to work with preloaded bitmaps.
The result is written to the fRect argument. Re-use a single instance for efficiency.
Parameters:
vRect - rectangle representing the view area to interpret.
fRect - rectangle instance to which the result will be written. Re-use for efficiency.
Find the area of the source file that is currently visible on screen, taking into account the
current scale, translation, orientation and clipped region. This is a convenience method; see
viewToFileRect(Rect, Rect).
Parameters:
fRect - rectangle instance to which the result will be written. Re-use for efficiency.
Swap the default region decoder implementation for one of your own. You must do this before setting the image file or
asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a
public default constructor.
Swap the default region decoder implementation for one of your own. You must do this before setting the image file or
asset, and you cannot use a custom decoder when using layout XML to set an asset name.
Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or
asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a
public default constructor.
Parameters:
bitmapDecoderClass - The ImageDecoder implementation to use.
Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or
asset, and you cannot use a custom decoder when using layout XML to set an asset name.
Calculate how much further the image can be panned in each direction. The results are set on
the supplied RectF and expressed as screen pixels. For example, if the image cannot be
panned any further towards the left, the value of RectF.left will be set to 0.
Parameters:
vTarget - target object for results. Re-use for efficiency.
setPanLimit
public final void setPanLimit(int panLimit)
Set the pan limiting style. See static fields. Normally PAN_LIMIT_INSIDE is best, for image galleries.
Parameters:
panLimit - a pan limit constant. See static fields.
setMinimumScaleType
public final void setMinimumScaleType(int scaleType)
Set the minimum scale type. See static fields. Normally SCALE_TYPE_CENTER_INSIDE is best, for image galleries.
Parameters:
scaleType - a scale type constant. See static fields.
setMaxScale
public final void setMaxScale(float maxScale)
Set the maximum scale allowed. A value of 1 means 1:1 pixels at maximum scale. You may wish to set this according
to screen density - on a retina screen, 1:1 may still be too small. Consider using setMinimumDpi(int),
which is density aware.
Parameters:
maxScale - maximum scale expressed as a source/view pixels ratio.
setMinScale
public final void setMinScale(float minScale)
Set the minimum scale allowed. A value of 1 means 1:1 pixels at minimum scale. You may wish to set this according
to screen density. Consider using setMaximumDpi(int), which is density aware.
Parameters:
minScale - minimum scale expressed as a source/view pixels ratio.
setMinimumDpi
public final void setMinimumDpi(int dpi)
This is a screen density aware alternative to setMaxScale(float); it allows you to express the maximum
allowed scale in terms of the minimum pixel density. This avoids the problem of 1:1 scale still being
too small on a high density screen. A sensible starting point is 160 - the default used by this view.
Parameters:
dpi - Source image pixel density at maximum zoom.
setMaximumDpi
public final void setMaximumDpi(int dpi)
This is a screen density aware alternative to setMinScale(float); it allows you to express the minimum
allowed scale in terms of the maximum pixel density.
Parameters:
dpi - Source image pixel density at minimum zoom.
getMaxScale
public float getMaxScale()
Returns the maximum allowed scale.
Returns:
the maximum scale as a source/view pixels ratio.
getMinScale
public final float getMinScale()
Returns the minimum allowed scale.
Returns:
the minimum scale as a source/view pixels ratio.
setMinimumTileDpi
public void setMinimumTileDpi(int minimumTileDpi)
By default, image tiles are at least as high resolution as the screen. For a retina screen this may not be
necessary, and may increase the likelihood of an OutOfMemoryError. This method sets a DPI at which higher
resolution tiles should be loaded. Using a lower number will on average use less memory but result in a lower
quality image. 160-240dpi will usually be enough. This should be called before setting the image source,
because it affects which tiles get loaded. When using an untiled source image this method has no effect.
Returns the source point at the center of the view.
Returns:
the source coordinates current at the center of the view.
getScale
public final float getScale()
Returns the current scale value.
Returns:
the current scale as a source/view pixels ratio.
setScaleAndCenter
public final void setScaleAndCenter(float scale,
@NullablePointF sCenter)
Externally change the scale and translation of the source image. This may be used with getCenter() and getScale()
to restore the scale and zoom after a screen rotate.
Parameters:
scale - New scale to set.
sCenter - New source image coordinate to center on the screen, subject to boundaries.
resetScaleAndCenter
public final void resetScaleAndCenter()
Fully zoom out and return the image to the middle of the screen. This might be useful if you have a view pager
and want images to be reset when the user has moved to another page.
isReady
public final boolean isReady()
Call to find whether the view is initialised, has dimensions, and will display an image on
the next draw. If a preview has been provided, it may be the preview that will be displayed
and the full size image may still be loading. If no preview was provided, this is called once
the base layer tiles of the full size image are loaded.
Returns:
true if the view is ready to display an image and accept touch gestures.
onReady
protected void onReady()
Called once when the view is initialised, has dimensions, and will display an image on the
next draw. This is triggered at the same time as SubsamplingScaleImageView.OnImageEventListener.onReady() but
allows a subclass to receive this event without using a listener.
isImageLoaded
public final boolean isImageLoaded()
Call to find whether the main image (base layer tiles where relevant) have been loaded. Before
this event the view is blank unless a preview was provided.
Returns:
true if the main image (not the preview) has been loaded and is ready to display.
onImageLoaded
protected void onImageLoaded()
Called once when the full size image or its base layer tiles have been loaded.
getSWidth
public final int getSWidth()
Get source width, ignoring orientation. If getOrientation() returns 90 or 270, you can use getSHeight()
for the apparent width.
Returns:
the source image width in pixels.
getSHeight
public final int getSHeight()
Get source height, ignoring orientation. If getOrientation() returns 90 or 270, you can use getSWidth()
for the apparent height.
Returns:
the source image height in pixels.
getOrientation
public final int getOrientation()
Returns the orientation setting. This can return ORIENTATION_USE_EXIF, in which case it doesn't tell you
the applied orientation of the image. For that, use getAppliedOrientation().
Returns:
the orientation setting. See static fields.
getAppliedOrientation
public final int getAppliedOrientation()
Returns the actual orientation of the image relative to the source file. This will be based on the source file's
EXIF orientation if you're using ORIENTATION_USE_EXIF. Values are 0, 90, 180, 270.
Returns:
the orientation applied after EXIF information has been extracted. See static fields.
Get the current state of the view (scale, center, orientation) for restoration after rotate. Will return null if
the view is not ready.
Returns:
an ImageViewState instance representing the current position of the image. null if the view isn't ready.
isZoomEnabled
public final boolean isZoomEnabled()
Returns true if zoom gesture detection is enabled.
Returns:
true if zoom gesture detection is enabled.
setZoomEnabled
public final void setZoomEnabled(boolean zoomEnabled)
Enable or disable zoom gesture detection. Disabling zoom locks the the current scale.
Parameters:
zoomEnabled - true to enable zoom gestures, false to disable.
isQuickScaleEnabled
public final boolean isQuickScaleEnabled()
Returns true if double tap & swipe to zoom is enabled.
Returns:
true if double tap & swipe to zoom is enabled.
setQuickScaleEnabled
public final void setQuickScaleEnabled(boolean quickScaleEnabled)
Enable or disable double tap & swipe to zoom.
Parameters:
quickScaleEnabled - true to enable quick scale, false to disable.
isPanEnabled
public final boolean isPanEnabled()
Returns true if pan gesture detection is enabled.
Returns:
true if pan gesture detection is enabled.
setPanEnabled
public final void setPanEnabled(boolean panEnabled)
Enable or disable pan gesture detection. Disabling pan causes the image to be centered. Pan
can still be changed from code.
Parameters:
panEnabled - true to enable panning, false to disable.
setTileBackgroundColor
public final void setTileBackgroundColor(int tileBgColor)
Set a solid color to render behind tiles, useful for displaying transparent PNGs.
Parameters:
tileBgColor - Background color for tiles.
setDoubleTapZoomScale
public final void setDoubleTapZoomScale(float doubleTapZoomScale)
Set the scale the image will zoom in to when double tapped. This also the scale point where a double tap is interpreted
as a zoom out gesture - if the scale is greater than 90% of this value, a double tap zooms out. Avoid using values
greater than the max zoom.
Parameters:
doubleTapZoomScale - New value for double tap gesture zoom scale.
setDoubleTapZoomDpi
public final void setDoubleTapZoomDpi(int dpi)
A density aware alternative to setDoubleTapZoomScale(float); this allows you to express the scale the
image will zoom in to when double tapped in terms of the image pixel density. Values lower than the max scale will
be ignored. A sensible starting point is 160 - the default used by this view.
Parameters:
dpi - New value for double tap gesture zoom scale.
setDoubleTapZoomStyle
public final void setDoubleTapZoomStyle(int doubleTapZoomStyle)
Set the type of zoom animation to be used for double taps. See static fields.
Parameters:
doubleTapZoomStyle - New value for zoom style.
setDoubleTapZoomDuration
public final void setDoubleTapZoomDuration(int durationMs)
Set the duration of the double tap zoom animation.
Provide an Executor to be used for loading images. By default, AsyncTask.THREAD_POOL_EXECUTOR
is used to minimise contention with other background work the app is doing. You can also choose
to use AsyncTask.SERIAL_EXECUTOR if you want to limit concurrent background tasks.
Alternatively you can supply an Executor of your own to avoid any contention. It is
strongly recommended to use a single executor instance for the life of your application, not
one per view instance.
Warning: If you are using a custom implementation of ImageRegionDecoder, and you
supply an executor with more than one thread, you must make sure your implementation supports
multi-threaded bitmap decoding or has appropriate internal synchronization. From SDK 21, Android's
BitmapRegionDecoder uses an internal lock so it is thread safe but
there is no advantage to using multiple threads.
public void setEagerLoadingEnabled(boolean eagerLoadingEnabled)
Enable or disable eager loading of tiles that appear on screen during gestures or animations,
while the gesture or animation is still in progress. By default this is enabled to improve
responsiveness, but it can result in tiles being loaded and discarded more rapidly than
necessary and reduce the animation frame rate on old/cheap devices. Disable this on older
devices if you see poor performance. Tiles will then be loaded only when gestures and animations
are completed.
Parameters:
eagerLoadingEnabled - true to enable loading during gestures, false to delay loading until gestures end
setDebug
public final void setDebug(boolean debug)
Enables visual debugging, showing tile boundaries and sizes.
Parameters:
debug - true to enable debugging, false to disable.
hasImage
public boolean hasImage()
Check if an image has been set. The image may not have been loaded and displayed yet.
Creates a panning animation builder, that when started will animate the image to place the given coordinates of
the image in the center of the screen. If doing this would move the image beyond the edges of the screen, the
image is instead animated to move the center point as near to the center of the screen as is allowed - it's
guaranteed to be on screen.
Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image
beyond the panning limits, the image is automatically panned during the animation.
Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image
beyond the panning limits, the image is automatically panned during the animation.
Decode an image. The URI can be in one of the following formats:
File: file:///scard/picture.jpg
Asset: file:///android_asset/picture.png
Resource: android.resource://com.example.app/drawable/picture
Initialise the decoder. When possible, perform initial setup work once in this method. The
dimensions of the image must be returned. The URI can be in one of the following formats:
File: file:///scard/picture.jpg
Asset: file:///android_asset/picture.png
Resource: android.resource://com.example.app/drawable/picture
Parameters:
context - Application context. A reference may be held, but must be cleared on recycle.
Decode a region of the image with the given sample size. This method is called off the UI
thread so it can safely load the image on the current thread. It is called from
AsyncTasks running in an executor that may have multiple threads, so
implementations must be thread safe. Adding synchronized to the method signature
is the simplest way to achieve this, but bear in mind the recycle() method can be
called concurrently.
Default implementation of ImageDecoder
using Android's BitmapFactory, based on the Skia library. This
works well in most circumstances and has reasonable performance, however it has some problems
with grayscale, indexed and CMYK images.
Decode an image. The URI can be in one of the following formats:
File: file:///scard/picture.jpg
Asset: file:///android_asset/picture.png
Resource: android.resource://com.example.app/drawable/picture
Default implementation of ImageRegionDecoder
using Android's BitmapRegionDecoder, based on the Skia library. This
works well in most circumstances and has reasonable performance due to the cached decoder instance,
however it has some problems with grayscale, indexed and CMYK images.
A ReadWriteLock is used to delegate responsibility for multi threading behaviour to the
BitmapRegionDecoder instance on SDK >= 21, whilst allowing this class to block until no
tiles are being loaded before recycling the decoder. In practice, BitmapRegionDecoder is
synchronized internally so this has no real impact on performance.
Initialise the decoder. When possible, perform initial setup work once in this method. The
dimensions of the image must be returned. The URI can be in one of the following formats:
File: file:///scard/picture.jpg
Asset: file:///android_asset/picture.png
Resource: android.resource://com.example.app/drawable/picture
Decode a region of the image with the given sample size. This method is called off the UI
thread so it can safely load the image on the current thread. It is called from
AsyncTasks running in an executor that may have multiple threads, so
implementations must be thread safe. Adding synchronized to the method signature
is the simplest way to achieve this, but bear in mind the ImageRegionDecoder.recycle() method can be
called concurrently.
One decoder is initialised when the class is initialised. This is enough to decode base layer tiles.
Additional decoders are initialised when a subregion of the image is first requested, which indicates
interaction with the view. Creation of additional encoders stops when allowAdditionalDecoder(int, long)
returns false. The default implementation takes into account the file size, number of CPU cores,
low memory status and a hard limit of 4. Extend this class to customise this.
WARNING: This class is highly experimental and not proven to be stable on a wide range of
devices. You are advised to test it thoroughly on all available devices, and code your app to use
SkiaImageRegionDecoder on old or low powered devices you could not test.
Acquire a read lock to prevent decoding overlapping with recycling, then check the pool still
exists and acquire a decoder to load the requested region.
Initialises the decoder pool. This method creates one decoder on the current thread and uses
it to decode the bounds, then spawns an independent thread to populate the pool with an
additional three decoders. The thread will abort if recycle() is called.
Acquire a read lock to prevent decoding overlapping with recycling, then check the pool still
exists and acquire a decoder to load the requested region. There is no check whether the pool
currently has decoders, because it's guaranteed to have one decoder after init(Context, Uri)
is called and be null once recycle() is called. In practice the view can't call this
method until after init(Context, Uri), so there will be no blocking on an empty pool.
Wait until all read locks held by decodeRegion(Rect, int) are released, then recycle
and destroy the pool. Elsewhere, when a read lock is acquired, we must check the pool is not null.
protected boolean allowAdditionalDecoder(int numberOfDecoders,
long fileLength)
Called before creating a new decoder. Based on number of CPU cores, available memory, and the
size of the image file, determines whether another decoder can be created. Subclasses can
override and customise this.
Parameters:
numberOfDecoders - the number of decoders that have been created so far
fileLength - the size of the image file in bytes. Creating another decoder will use approximately this much native memory.
An event listener for animations, allows events to be triggered when an animation completes,
is aborted by another animation starting, or is aborted by a touch event.
================================================
FILE: docs/javadoc/help-doc.html
================================================
API Help (library 3.10.0 API)
This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.
Overview
The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.
Package
Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain six categories:
Interfaces (italic)
Classes
Enums
Exceptions
Errors
Annotation Types
Class/Interface
Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:
Class inheritance diagram
Direct Subclasses
All Known Subinterfaces
All Known Implementing Classes
Class/interface declaration
Class/interface description
Nested Class Summary
Field Summary
Constructor Summary
Method Summary
Field Detail
Constructor Detail
Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.
Annotation Type
Each annotation type has its own separate page with the following sections:
Annotation Type declaration
Annotation Type description
Required Element Summary
Optional Element Summary
Element Detail
Enum
Each enum has its own separate page with the following sections:
Enum declaration
Enum description
Enum Constant Summary
Enum Constant Detail
Tree (Class Hierarchy)
There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.
Deprecated API
The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.
Index
The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.
Prev/Next
These links take you to the next or previous class, interface, package, or related page.
Frames/No Frames
These links show and hide the HTML frames. All pages are available with or without frames.
All Classes
The All Classes link shows all classes and interfaces except non-static nested types.
Serialized Form
Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description.
Acquire a read lock to prevent decoding overlapping with recycling, then check the pool still
exists and acquire a decoder to load the requested region.
Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be
displayed until the full size image is loaded, starting with a given orientation setting, scale and center.
This is a screen density aware alternative to SubsamplingScaleImageView.setMinScale(float); it allows you to express the minimum
allowed scale in terms of the maximum pixel density.
This is a screen density aware alternative to SubsamplingScaleImageView.setMaxScale(float); it allows you to express the maximum
allowed scale in terms of the minimum pixel density.
An event listener for animations, allows events to be triggered when an animation completes,
is aborted by another animation starting, or is aborted by a touch event.
Converts a rectangle within the view to the corresponding rectangle from the source file, taking
into account the current scale, translation, orientation and clipped region.
Find the area of the source file that is currently visible on screen, taking into account the
current scale, translation, orientation and clipped region.
================================================
FILE: docs/javadoc/stylesheet.css
================================================
/* Javadoc style sheet */
/*
Overall document style
*/
@import url('resources/fonts/dejavu.css');
body {
background-color:#ffffff;
color:#353833;
font-family:'DejaVu Sans', Arial, Helvetica, sans-serif;
font-size:14px;
margin:0;
}
a:link, a:visited {
text-decoration:none;
color:#4A6782;
}
a:hover, a:focus {
text-decoration:none;
color:#bb7a2a;
}
a:active {
text-decoration:none;
color:#4A6782;
}
a[name] {
color:#353833;
}
a[name]:hover {
text-decoration:none;
color:#353833;
}
pre {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
}
h1 {
font-size:20px;
}
h2 {
font-size:18px;
}
h3 {
font-size:16px;
font-style:italic;
}
h4 {
font-size:13px;
}
h5 {
font-size:12px;
}
h6 {
font-size:11px;
}
ul {
list-style-type:disc;
}
code, tt {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
padding-top:4px;
margin-top:8px;
line-height:1.4em;
}
dt code {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
padding-top:4px;
}
table tr td dt code {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
vertical-align:top;
padding-top:4px;
}
sup {
font-size:8px;
}
/*
Document title and Copyright styles
*/
.clear {
clear:both;
height:0px;
overflow:hidden;
}
.aboutLanguage {
float:right;
padding:0px 21px;
font-size:11px;
z-index:200;
margin-top:-9px;
}
.legalCopy {
margin-left:.5em;
}
.bar a, .bar a:link, .bar a:visited, .bar a:active {
color:#FFFFFF;
text-decoration:none;
}
.bar a:hover, .bar a:focus {
color:#bb7a2a;
}
.tab {
background-color:#0066FF;
color:#ffffff;
padding:8px;
width:5em;
font-weight:bold;
}
/*
Navigation bar styles
*/
.bar {
background-color:#4D7A97;
color:#FFFFFF;
padding:.8em .5em .4em .8em;
height:auto;/*height:1.8em;*/
font-size:11px;
margin:0;
}
.topNav {
background-color:#4D7A97;
color:#FFFFFF;
float:left;
padding:0;
width:100%;
clear:right;
height:2.8em;
padding-top:10px;
overflow:hidden;
font-size:12px;
}
.bottomNav {
margin-top:10px;
background-color:#4D7A97;
color:#FFFFFF;
float:left;
padding:0;
width:100%;
clear:right;
height:2.8em;
padding-top:10px;
overflow:hidden;
font-size:12px;
}
.subNav {
background-color:#dee3e9;
float:left;
width:100%;
overflow:hidden;
font-size:12px;
}
.subNav div {
clear:left;
float:left;
padding:0 0 5px 6px;
text-transform:uppercase;
}
ul.navList, ul.subNavList {
float:left;
margin:0 25px 0 0;
padding:0;
}
ul.navList li{
list-style:none;
float:left;
padding: 5px 6px;
text-transform:uppercase;
}
ul.subNavList li{
list-style:none;
float:left;
}
.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited {
color:#FFFFFF;
text-decoration:none;
text-transform:uppercase;
}
.topNav a:hover, .bottomNav a:hover {
text-decoration:none;
color:#bb7a2a;
text-transform:uppercase;
}
.navBarCell1Rev {
background-color:#F8981D;
color:#253441;
margin: auto 5px;
}
.skipNav {
position:absolute;
top:auto;
left:-9999px;
overflow:hidden;
}
/*
Page header and footer styles
*/
.header, .footer {
clear:both;
margin:0 20px;
padding:5px 0 0 0;
}
.indexHeader {
margin:10px;
position:relative;
}
.indexHeader span{
margin-right:15px;
}
.indexHeader h1 {
font-size:13px;
}
.title {
color:#2c4557;
margin:10px 0;
}
.subTitle {
margin:5px 0 0 0;
}
.header ul {
margin:0 0 15px 0;
padding:0;
}
.footer ul {
margin:20px 0 5px 0;
}
.header ul li, .footer ul li {
list-style:none;
font-size:13px;
}
/*
Heading styles
*/
div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 {
background-color:#dee3e9;
border:1px solid #d0d9e0;
margin:0 0 6px -8px;
padding:7px 5px;
}
ul.blockList ul.blockList ul.blockList li.blockList h3 {
background-color:#dee3e9;
border:1px solid #d0d9e0;
margin:0 0 6px -8px;
padding:7px 5px;
}
ul.blockList ul.blockList li.blockList h3 {
padding:0;
margin:15px 0;
}
ul.blockList li.blockList h2 {
padding:0px 0 20px 0;
}
/*
Page layout container styles
*/
.contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer {
clear:both;
padding:10px 20px;
position:relative;
}
.indexContainer {
margin:10px;
position:relative;
font-size:12px;
}
.indexContainer h2 {
font-size:13px;
padding:0 0 3px 0;
}
.indexContainer ul {
margin:0;
padding:0;
}
.indexContainer ul li {
list-style:none;
padding-top:2px;
}
.contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt {
font-size:12px;
font-weight:bold;
margin:10px 0 0 0;
color:#4E4E4E;
}
.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd {
margin:5px 0 10px 0px;
font-size:14px;
font-family:'DejaVu Sans Mono',monospace;
}
.serializedFormContainer dl.nameValue dt {
margin-left:1px;
font-size:1.1em;
display:inline;
font-weight:bold;
}
.serializedFormContainer dl.nameValue dd {
margin:0 0 0 1px;
font-size:1.1em;
display:inline;
}
/*
List styles
*/
ul.horizontal li {
display:inline;
font-size:0.9em;
}
ul.inheritance {
margin:0;
padding:0;
}
ul.inheritance li {
display:inline;
list-style:none;
}
ul.inheritance li ul.inheritance {
margin-left:15px;
padding-left:15px;
padding-top:1px;
}
ul.blockList, ul.blockListLast {
margin:10px 0 10px 0;
padding:0;
}
ul.blockList li.blockList, ul.blockListLast li.blockList {
list-style:none;
margin-bottom:15px;
line-height:1.4;
}
ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList {
padding:0px 20px 5px 10px;
border:1px solid #ededed;
background-color:#f8f8f8;
}
ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList {
padding:0 0 5px 8px;
background-color:#ffffff;
border:none;
}
ul.blockList ul.blockList ul.blockList ul.blockList li.blockList {
margin-left:0;
padding-left:0;
padding-bottom:15px;
border:none;
}
ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast {
list-style:none;
border-bottom:none;
padding-bottom:0;
}
table tr td dl, table tr td dl dt, table tr td dl dd {
margin-top:0;
margin-bottom:1px;
}
/*
Table styles
*/
.overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary {
width:100%;
border-left:1px solid #EEE;
border-right:1px solid #EEE;
border-bottom:1px solid #EEE;
}
.overviewSummary, .memberSummary {
padding:0px;
}
.overviewSummary caption, .memberSummary caption, .typeSummary caption,
.useSummary caption, .constantsSummary caption, .deprecatedSummary caption {
position:relative;
text-align:left;
background-repeat:no-repeat;
color:#253441;
font-weight:bold;
clear:none;
overflow:hidden;
padding:0px;
padding-top:10px;
padding-left:1px;
margin:0px;
white-space:pre;
}
.overviewSummary caption a:link, .memberSummary caption a:link, .typeSummary caption a:link,
.useSummary caption a:link, .constantsSummary caption a:link, .deprecatedSummary caption a:link,
.overviewSummary caption a:hover, .memberSummary caption a:hover, .typeSummary caption a:hover,
.useSummary caption a:hover, .constantsSummary caption a:hover, .deprecatedSummary caption a:hover,
.overviewSummary caption a:active, .memberSummary caption a:active, .typeSummary caption a:active,
.useSummary caption a:active, .constantsSummary caption a:active, .deprecatedSummary caption a:active,
.overviewSummary caption a:visited, .memberSummary caption a:visited, .typeSummary caption a:visited,
.useSummary caption a:visited, .constantsSummary caption a:visited, .deprecatedSummary caption a:visited {
color:#FFFFFF;
}
.overviewSummary caption span, .memberSummary caption span, .typeSummary caption span,
.useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span {
white-space:nowrap;
padding-top:5px;
padding-left:12px;
padding-right:12px;
padding-bottom:7px;
display:inline-block;
float:left;
background-color:#F8981D;
border: none;
height:16px;
}
.memberSummary caption span.activeTableTab span {
white-space:nowrap;
padding-top:5px;
padding-left:12px;
padding-right:12px;
margin-right:3px;
display:inline-block;
float:left;
background-color:#F8981D;
height:16px;
}
.memberSummary caption span.tableTab span {
white-space:nowrap;
padding-top:5px;
padding-left:12px;
padding-right:12px;
margin-right:3px;
display:inline-block;
float:left;
background-color:#4D7A97;
height:16px;
}
.memberSummary caption span.tableTab, .memberSummary caption span.activeTableTab {
padding-top:0px;
padding-left:0px;
padding-right:0px;
background-image:none;
float:none;
display:inline;
}
.overviewSummary .tabEnd, .memberSummary .tabEnd, .typeSummary .tabEnd,
.useSummary .tabEnd, .constantsSummary .tabEnd, .deprecatedSummary .tabEnd {
display:none;
width:5px;
position:relative;
float:left;
background-color:#F8981D;
}
.memberSummary .activeTableTab .tabEnd {
display:none;
width:5px;
margin-right:3px;
position:relative;
float:left;
background-color:#F8981D;
}
.memberSummary .tableTab .tabEnd {
display:none;
width:5px;
margin-right:3px;
position:relative;
background-color:#4D7A97;
float:left;
}
.overviewSummary td, .memberSummary td, .typeSummary td,
.useSummary td, .constantsSummary td, .deprecatedSummary td {
text-align:left;
padding:0px 0px 12px 10px;
}
th.colOne, th.colFirst, th.colLast, .useSummary th, .constantsSummary th,
td.colOne, td.colFirst, td.colLast, .useSummary td, .constantsSummary td{
vertical-align:top;
padding-right:0px;
padding-top:8px;
padding-bottom:3px;
}
th.colFirst, th.colLast, th.colOne, .constantsSummary th {
background:#dee3e9;
text-align:left;
padding:8px 3px 3px 7px;
}
td.colFirst, th.colFirst {
white-space:nowrap;
font-size:13px;
}
td.colLast, th.colLast {
font-size:13px;
}
td.colOne, th.colOne {
font-size:13px;
}
.overviewSummary td.colFirst, .overviewSummary th.colFirst,
.useSummary td.colFirst, .useSummary th.colFirst,
.overviewSummary td.colOne, .overviewSummary th.colOne,
.memberSummary td.colFirst, .memberSummary th.colFirst,
.memberSummary td.colOne, .memberSummary th.colOne,
.typeSummary td.colFirst{
width:25%;
vertical-align:top;
}
td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover {
font-weight:bold;
}
.tableSubHeadingColor {
background-color:#EEEEFF;
}
.altColor {
background-color:#FFFFFF;
}
.rowColor {
background-color:#EEEEEF;
}
/*
Content styles
*/
.description pre {
margin-top:0;
}
.deprecatedContent {
margin:0;
padding:10px 0;
}
.docSummary {
padding:0;
}
ul.blockList ul.blockList ul.blockList li.blockList h3 {
font-style:normal;
}
div.block {
font-size:14px;
font-family:'DejaVu Serif', Georgia, "Times New Roman", Times, serif;
}
td.colLast div {
padding-top:0px;
}
td.colLast a {
padding-bottom:3px;
}
/*
Formatting effect styles
*/
.sourceLineNo {
color:green;
padding:0 30px 0 0;
}
h1.hidden {
visibility:hidden;
overflow:hidden;
font-size:10px;
}
.block {
display:block;
margin:3px 10px 2px 0px;
color:#474747;
}
.deprecatedLabel, .descfrmTypeLabel, .memberNameLabel, .memberNameLink,
.overrideSpecifyLabel, .packageHierarchyLabel, .paramLabel, .returnLabel,
.seeLabel, .simpleTagLabel, .throwsLabel, .typeNameLabel, .typeNameLink {
font-weight:bold;
}
.deprecationComment, .emphasizedPhrase, .interfaceName {
font-style:italic;
}
div.block div.block span.deprecationComment, div.block div.block span.emphasizedPhrase,
div.block div.block span.interfaceName {
font-style:normal;
}
div.contentContainer ul.blockList li.blockList h2{
padding-bottom:0px;
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Tue Dec 29 20:26:01 GMT 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
android.enableJetifier=true
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: library/build.gradle
================================================
apply plugin: 'com.android.library'
group = 'com.davemorrissey.labs'
archivesBaseName = 'subsampling-scale-image-view-androidx'
version = '3.10.0'
android {
compileSdkVersion 30
defaultConfig {
minSdkVersion 14
targetSdkVersion 30
consumerProguardFiles 'proguard-rules.txt'
}
}
configurations {
javadocs
}
dependencies {
implementation "androidx.appcompat:appcompat:1.2.0"
javadocs 'androidx.annotation:annotation:1.1.0'
javadocs 'androidx.exifinterface:exifinterface:1.3.2'
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'androidx.exifinterface:exifinterface:1.3.2'
}
task javadoc(type: Javadoc) {
failOnError false
source = android.sourceSets.main.java.sourceFiles
destinationDir = rootProject.file("docs/javadoc")
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
classpath += configurations.compile
classpath += configurations.javadocs
options.noTimestamp = true
options.links = ['https://developer.android.com/reference/']
}
apply from: rootProject.file('release.gradle')
================================================
FILE: library/proguard-rules.txt
================================================
-keep class com.davemorrissey.labs.subscaleview.** { *; }
================================================
FILE: library/src/main/AndroidManifest.xml
================================================
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/ImageSource.java
================================================
package com.davemorrissey.labs.subscaleview;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import androidx.annotation.NonNull;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
/**
* Helper class used to set the source and additional attributes from a variety of sources. Supports
* use of a bitmap, asset, resource, external file or any other URI.
*
* When you are using a preview image, you must set the dimensions of the full size image on the
* ImageSource object for the full size image using the {@link #dimensions(int, int)} method.
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public final class ImageSource {
static final String FILE_SCHEME = "file:///";
static final String ASSET_SCHEME = "file:///android_asset/";
private final Uri uri;
private final Bitmap bitmap;
private final Integer resource;
private boolean tile;
private int sWidth;
private int sHeight;
private Rect sRegion;
private boolean cached;
private ImageSource(Bitmap bitmap, boolean cached) {
this.bitmap = bitmap;
this.uri = null;
this.resource = null;
this.tile = false;
this.sWidth = bitmap.getWidth();
this.sHeight = bitmap.getHeight();
this.cached = cached;
}
private ImageSource(@NonNull Uri uri) {
// #114 If file doesn't exist, attempt to url decode the URI and try again
String uriString = uri.toString();
if (uriString.startsWith(FILE_SCHEME)) {
File uriFile = new File(uriString.substring(FILE_SCHEME.length() - 1));
if (!uriFile.exists()) {
try {
uri = Uri.parse(URLDecoder.decode(uriString, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// Fallback to encoded URI. This exception is not expected.
}
}
}
this.bitmap = null;
this.uri = uri;
this.resource = null;
this.tile = true;
}
private ImageSource(int resource) {
this.bitmap = null;
this.uri = null;
this.resource = resource;
this.tile = true;
}
/**
* Create an instance from a resource. The correct resource for the device screen resolution will be used.
* @param resId resource ID.
* @return an {@link ImageSource} instance.
*/
@NonNull
public static ImageSource resource(int resId) {
return new ImageSource(resId);
}
/**
* Create an instance from an asset name.
* @param assetName asset name.
* @return an {@link ImageSource} instance.
*/
@NonNull
public static ImageSource asset(@NonNull String assetName) {
//noinspection ConstantConditions
if (assetName == null) {
throw new NullPointerException("Asset name must not be null");
}
return uri(ASSET_SCHEME + assetName);
}
/**
* Create an instance from a URI. If the URI does not start with a scheme, it's assumed to be the URI
* of a file.
* @param uri image URI.
* @return an {@link ImageSource} instance.
*/
@NonNull
public static ImageSource uri(@NonNull String uri) {
//noinspection ConstantConditions
if (uri == null) {
throw new NullPointerException("Uri must not be null");
}
if (!uri.contains("://")) {
if (uri.startsWith("/")) {
uri = uri.substring(1);
}
uri = FILE_SCHEME + uri;
}
return new ImageSource(Uri.parse(uri));
}
/**
* Create an instance from a URI.
* @param uri image URI.
* @return an {@link ImageSource} instance.
*/
@NonNull
public static ImageSource uri(@NonNull Uri uri) {
//noinspection ConstantConditions
if (uri == null) {
throw new NullPointerException("Uri must not be null");
}
return new ImageSource(uri);
}
/**
* Provide a loaded bitmap for display.
* @param bitmap bitmap to be displayed.
* @return an {@link ImageSource} instance.
*/
@NonNull
public static ImageSource bitmap(@NonNull Bitmap bitmap) {
//noinspection ConstantConditions
if (bitmap == null) {
throw new NullPointerException("Bitmap must not be null");
}
return new ImageSource(bitmap, false);
}
/**
* Provide a loaded and cached bitmap for display. This bitmap will not be recycled when it is no
* longer needed. Use this method if you loaded the bitmap with an image loader such as Picasso
* or Volley.
* @param bitmap bitmap to be displayed.
* @return an {@link ImageSource} instance.
*/
@NonNull
public static ImageSource cachedBitmap(@NonNull Bitmap bitmap) {
//noinspection ConstantConditions
if (bitmap == null) {
throw new NullPointerException("Bitmap must not be null");
}
return new ImageSource(bitmap, true);
}
/**
* Enable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap.,
* and tiling cannot be disabled when displaying a region of the source image.
* @return this instance for chaining.
*/
@NonNull
public ImageSource tilingEnabled() {
return tiling(true);
}
/**
* Disable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap,
* and tiling cannot be disabled when displaying a region of the source image.
* @return this instance for chaining.
*/
@NonNull
public ImageSource tilingDisabled() {
return tiling(false);
}
/**
* Enable or disable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap,
* and tiling cannot be disabled when displaying a region of the source image.
* @param tile whether tiling should be enabled.
* @return this instance for chaining.
*/
@NonNull
public ImageSource tiling(boolean tile) {
this.tile = tile;
return this;
}
/**
* Use a region of the source image. Region must be set independently for the full size image and the preview if
* you are using one.
* @param sRegion the region of the source image to be displayed.
* @return this instance for chaining.
*/
@NonNull
public ImageSource region(Rect sRegion) {
this.sRegion = sRegion;
setInvariants();
return this;
}
/**
* Declare the dimensions of the image. This is only required for a full size image, when you are specifying a URI
* and also a preview image. When displaying a bitmap object, or not using a preview, you do not need to declare
* the image dimensions. Note if the declared dimensions are found to be incorrect, the view will reset.
* @param sWidth width of the source image.
* @param sHeight height of the source image.
* @return this instance for chaining.
*/
@NonNull
public ImageSource dimensions(int sWidth, int sHeight) {
if (bitmap == null) {
this.sWidth = sWidth;
this.sHeight = sHeight;
}
setInvariants();
return this;
}
private void setInvariants() {
if (this.sRegion != null) {
this.tile = true;
this.sWidth = this.sRegion.width();
this.sHeight = this.sRegion.height();
}
}
protected final Uri getUri() {
return uri;
}
protected final Bitmap getBitmap() {
return bitmap;
}
protected final Integer getResource() {
return resource;
}
protected final boolean getTile() {
return tile;
}
protected final int getSWidth() {
return sWidth;
}
protected final int getSHeight() {
return sHeight;
}
protected final Rect getSRegion() {
return sRegion;
}
protected final boolean isCached() {
return cached;
}
}
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/ImageViewState.java
================================================
package com.davemorrissey.labs.subscaleview;
import android.graphics.PointF;
import androidx.annotation.NonNull;
import java.io.Serializable;
/**
* Wraps the scale, center and orientation of a displayed image for easy restoration on screen rotate.
*/
@SuppressWarnings("WeakerAccess")
public class ImageViewState implements Serializable {
private final float scale;
private final float centerX;
private final float centerY;
private final int orientation;
public ImageViewState(float scale, @NonNull PointF center, int orientation) {
this.scale = scale;
this.centerX = center.x;
this.centerY = center.y;
this.orientation = orientation;
}
public float getScale() {
return scale;
}
@NonNull public PointF getCenter() {
return new PointF(centerX, centerY);
}
public int getOrientation() {
return orientation;
}
}
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/SubsamplingScaleImageView.java
================================================
package com.davemorrissey.labs.subscaleview;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import androidx.annotation.Nullable;
import androidx.exifinterface.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import com.davemorrissey.labs.subscaleview.R.styleable;
import com.davemorrissey.labs.subscaleview.decoder.CompatDecoderFactory;
import com.davemorrissey.labs.subscaleview.decoder.DecoderFactory;
import com.davemorrissey.labs.subscaleview.decoder.ImageDecoder;
import com.davemorrissey.labs.subscaleview.decoder.ImageRegionDecoder;
import com.davemorrissey.labs.subscaleview.decoder.SkiaImageDecoder;
import com.davemorrissey.labs.subscaleview.decoder.SkiaImageRegionDecoder;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
*
* Displays an image subsampled as necessary to avoid loading too much image data into memory. After zooming in,
* a set of image tiles subsampled at higher resolution are loaded and displayed over the base layer. During pan and
* zoom, tiles off screen or higher/lower resolution than required are discarded from memory.
*
* Tiles are no larger than the max supported bitmap size, so with large images tiling may be used even when zoomed out.
*
* v prefixes - coordinates, translations and distances measured in screen (view) pixels
*
* s prefixes - coordinates, translations and distances measured in rotated and cropped source image pixels (scaled)
*
* f prefixes - coordinates, translations and distances measured in original unrotated, uncropped source file pixels
*
*/
@SuppressWarnings("unused")
public class SubsamplingScaleImageView extends View {
private static final String TAG = SubsamplingScaleImageView.class.getSimpleName();
/** Attempt to use EXIF information on the image to rotate it. Works for external files only. */
public static final int ORIENTATION_USE_EXIF = -1;
/** Display the image file in its native orientation. */
public static final int ORIENTATION_0 = 0;
/** Rotate the image 90 degrees clockwise. */
public static final int ORIENTATION_90 = 90;
/** Rotate the image 180 degrees. */
public static final int ORIENTATION_180 = 180;
/** Rotate the image 270 degrees clockwise. */
public static final int ORIENTATION_270 = 270;
private static final List VALID_ORIENTATIONS = Arrays.asList(ORIENTATION_0, ORIENTATION_90, ORIENTATION_180, ORIENTATION_270, ORIENTATION_USE_EXIF);
/** During zoom animation, keep the point of the image that was tapped in the same place, and scale the image around it. */
public static final int ZOOM_FOCUS_FIXED = 1;
/** During zoom animation, move the point of the image that was tapped to the center of the screen. */
public static final int ZOOM_FOCUS_CENTER = 2;
/** Zoom in to and center the tapped point immediately without animating. */
public static final int ZOOM_FOCUS_CENTER_IMMEDIATE = 3;
private static final List VALID_ZOOM_STYLES = Arrays.asList(ZOOM_FOCUS_FIXED, ZOOM_FOCUS_CENTER, ZOOM_FOCUS_CENTER_IMMEDIATE);
/** Quadratic ease out. Not recommended for scale animation, but good for panning. */
public static final int EASE_OUT_QUAD = 1;
/** Quadratic ease in and out. */
public static final int EASE_IN_OUT_QUAD = 2;
private static final List VALID_EASING_STYLES = Arrays.asList(EASE_IN_OUT_QUAD, EASE_OUT_QUAD);
/** 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. */
public static final int PAN_LIMIT_INSIDE = 1;
/** 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. */
public static final int PAN_LIMIT_OUTSIDE = 2;
/** 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. */
public static final int PAN_LIMIT_CENTER = 3;
private static final List VALID_PAN_LIMITS = Arrays.asList(PAN_LIMIT_INSIDE, PAN_LIMIT_OUTSIDE, PAN_LIMIT_CENTER);
/** 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. */
public static final int SCALE_TYPE_CENTER_INSIDE = 1;
/** 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. */
public static final int SCALE_TYPE_CENTER_CROP = 2;
/** Scale the image so that both dimensions of the image will be equal to or less than the maxScale and equal to or larger than minScale. The image is then centered in the view. */
public static final int SCALE_TYPE_CUSTOM = 3;
/** Scale the image so that both dimensions of the image will be equal to or larger than the corresponding dimension of the view. The top left is shown. */
public static final int SCALE_TYPE_START = 4;
private static final List VALID_SCALE_TYPES = Arrays.asList(SCALE_TYPE_CENTER_CROP, SCALE_TYPE_CENTER_INSIDE, SCALE_TYPE_CUSTOM, SCALE_TYPE_START);
/** State change originated from animation. */
public static final int ORIGIN_ANIM = 1;
/** State change originated from touch gesture. */
public static final int ORIGIN_TOUCH = 2;
/** State change originated from a fling momentum anim. */
public static final int ORIGIN_FLING = 3;
/** State change originated from a double tap zoom anim. */
public static final int ORIGIN_DOUBLE_TAP_ZOOM = 4;
// Bitmap (preview or full image)
private Bitmap bitmap;
// Whether the bitmap is a preview image
private boolean bitmapIsPreview;
// Specifies if a cache handler is also referencing the bitmap. Do not recycle if so.
private boolean bitmapIsCached;
// Uri of full size image
private Uri uri;
// Sample size used to display the whole image when fully zoomed out
private int fullImageSampleSize;
// Map of zoom level to tile grid
private Map> tileMap;
// Overlay tile boundaries and other info
private boolean debug;
// Image orientation setting
private int orientation = ORIENTATION_0;
// Max scale allowed (prevent infinite zoom)
private float maxScale = 2F;
// Min scale allowed (prevent infinite zoom)
private float minScale = minScale();
// Density to reach before loading higher resolution tiles
private int minimumTileDpi = -1;
// Pan limiting style
private int panLimit = PAN_LIMIT_INSIDE;
// Minimum scale type
private int minimumScaleType = SCALE_TYPE_CENTER_INSIDE;
// overrides for the dimensions of the generated tiles
public static final int TILE_SIZE_AUTO = Integer.MAX_VALUE;
private int maxTileWidth = TILE_SIZE_AUTO;
private int maxTileHeight = TILE_SIZE_AUTO;
// An executor service for loading of images
private Executor executor = AsyncTask.THREAD_POOL_EXECUTOR;
// Whether tiles should be loaded while gestures and animations are still in progress
private boolean eagerLoadingEnabled = true;
// Gesture detection settings
private boolean panEnabled = true;
private boolean zoomEnabled = true;
private boolean quickScaleEnabled = true;
// Double tap zoom behaviour
private float doubleTapZoomScale = 1F;
private int doubleTapZoomStyle = ZOOM_FOCUS_FIXED;
private int doubleTapZoomDuration = 500;
// Current scale and scale at start of zoom
private float scale;
private float scaleStart;
// Screen coordinate of top-left corner of source image
private PointF vTranslate;
private PointF vTranslateStart;
private PointF vTranslateBefore;
// Source coordinate to center on, used when new position is set externally before view is ready
private Float pendingScale;
private PointF sPendingCenter;
private PointF sRequestedCenter;
// Source image dimensions and orientation - dimensions relate to the unrotated image
private int sWidth;
private int sHeight;
private int sOrientation;
private Rect sRegion;
private Rect pRegion;
// Is two-finger zooming in progress
private boolean isZooming;
// Is one-finger panning in progress
private boolean isPanning;
// Is quick-scale gesture in progress
private boolean isQuickScaling;
// Max touches used in current gesture
private int maxTouchCount;
// Fling detector
private GestureDetector detector;
private GestureDetector singleDetector;
// Tile and image decoding
private ImageRegionDecoder decoder;
private final ReadWriteLock decoderLock = new ReentrantReadWriteLock(true);
private DecoderFactory extends ImageDecoder> bitmapDecoderFactory = new CompatDecoderFactory(SkiaImageDecoder.class);
private DecoderFactory extends ImageRegionDecoder> regionDecoderFactory = new CompatDecoderFactory(SkiaImageRegionDecoder.class);
// Debug values
private PointF vCenterStart;
private float vDistStart;
// Current quickscale state
private final float quickScaleThreshold;
private float quickScaleLastDistance;
private boolean quickScaleMoved;
private PointF quickScaleVLastPoint;
private PointF quickScaleSCenter;
private PointF quickScaleVStart;
// Scale and center animation tracking
private Anim anim;
// Whether a ready notification has been sent to subclasses
private boolean readySent;
// Whether a base layer loaded notification has been sent to subclasses
private boolean imageLoadedSent;
// Event listener
private OnImageEventListener onImageEventListener;
// Scale and center listener
private OnStateChangedListener onStateChangedListener;
// Long click listener
private OnLongClickListener onLongClickListener;
// Long click handler
private final Handler handler;
private static final int MESSAGE_LONG_CLICK = 1;
// Paint objects created once and reused for efficiency
private Paint bitmapPaint;
private Paint debugTextPaint;
private Paint debugLinePaint;
private Paint tileBgPaint;
// Volatile fields used to reduce object creation
private ScaleAndTranslate satTemp;
private Matrix matrix;
private RectF sRect;
private final float[] srcArray = new float[8];
private final float[] dstArray = new float[8];
//The logical density of the display
private final float density;
// A global preference for bitmap format, available to decoder classes that respect it
private static Bitmap.Config preferredBitmapConfig;
public SubsamplingScaleImageView(Context context, AttributeSet attr) {
super(context, attr);
density = getResources().getDisplayMetrics().density;
setMinimumDpi(160);
setDoubleTapZoomDpi(160);
setMinimumTileDpi(320);
setGestureDetector(context);
this.handler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message message) {
if (message.what == MESSAGE_LONG_CLICK && onLongClickListener != null) {
maxTouchCount = 0;
SubsamplingScaleImageView.super.setOnLongClickListener(onLongClickListener);
performLongClick();
SubsamplingScaleImageView.super.setOnLongClickListener(null);
}
return true;
}
});
// Handle XML attributes
if (attr != null) {
TypedArray typedAttr = getContext().obtainStyledAttributes(attr, styleable.SubsamplingScaleImageView);
if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_assetName)) {
String assetName = typedAttr.getString(styleable.SubsamplingScaleImageView_assetName);
if (assetName != null && assetName.length() > 0) {
setImage(ImageSource.asset(assetName).tilingEnabled());
}
}
if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_src)) {
int resId = typedAttr.getResourceId(styleable.SubsamplingScaleImageView_src, 0);
if (resId > 0) {
setImage(ImageSource.resource(resId).tilingEnabled());
}
}
if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_panEnabled)) {
setPanEnabled(typedAttr.getBoolean(styleable.SubsamplingScaleImageView_panEnabled, true));
}
if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_zoomEnabled)) {
setZoomEnabled(typedAttr.getBoolean(styleable.SubsamplingScaleImageView_zoomEnabled, true));
}
if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_quickScaleEnabled)) {
setQuickScaleEnabled(typedAttr.getBoolean(styleable.SubsamplingScaleImageView_quickScaleEnabled, true));
}
if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_tileBackgroundColor)) {
setTileBackgroundColor(typedAttr.getColor(styleable.SubsamplingScaleImageView_tileBackgroundColor, Color.argb(0, 0, 0, 0)));
}
typedAttr.recycle();
}
quickScaleThreshold = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, context.getResources().getDisplayMetrics());
}
public SubsamplingScaleImageView(Context context) {
this(context, null);
}
/**
* Get the current preferred configuration for decoding bitmaps. {@link ImageDecoder} and {@link ImageRegionDecoder}
* instances can read this and use it when decoding images.
* @return the preferred bitmap configuration, or null if none has been set.
*/
public static Bitmap.Config getPreferredBitmapConfig() {
return preferredBitmapConfig;
}
/**
* Set a global preferred bitmap config shared by all view instances and applied to new instances
* initialised after the call is made. This is a hint only; the bundled {@link ImageDecoder} and
* {@link ImageRegionDecoder} classes all respect this (except when they were constructed with
* an instance-specific config) but custom decoder classes will not.
* @param preferredBitmapConfig the bitmap configuration to be used by future instances of the view. Pass null to restore the default.
*/
public static void setPreferredBitmapConfig(Bitmap.Config preferredBitmapConfig) {
SubsamplingScaleImageView.preferredBitmapConfig = preferredBitmapConfig;
}
/**
* Sets the image orientation. It's best to call this before setting the image file or asset, because it may waste
* loading of tiles. However, this can be freely called at any time.
* @param orientation orientation to be set. See ORIENTATION_ static fields for valid values.
*/
public final void setOrientation(int orientation) {
if (!VALID_ORIENTATIONS.contains(orientation)) {
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
this.orientation = orientation;
reset(false);
invalidate();
requestLayout();
}
/**
* Set the image source from a bitmap, resource, asset, file or other URI.
* @param imageSource Image source.
*/
public final void setImage(@NonNull ImageSource imageSource) {
setImage(imageSource, null, null);
}
/**
* Set the image source from a bitmap, resource, asset, file or other URI, starting with a given orientation
* setting, scale and center. This is the best method to use when you want scale and center to be restored
* after screen orientation change; it avoids any redundant loading of tiles in the wrong orientation.
* @param imageSource Image source.
* @param state State to be restored. Nullable.
*/
public final void setImage(@NonNull ImageSource imageSource, ImageViewState state) {
setImage(imageSource, null, state);
}
/**
* Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be
* displayed until the full size image is loaded.
*
* You must declare the dimensions of the full size image by calling {@link ImageSource#dimensions(int, int)}
* on the imageSource object. The preview source will be ignored if you don't provide dimensions,
* and if you provide a bitmap for the full size image.
* @param imageSource Image source. Dimensions must be declared.
* @param previewSource Optional source for a preview image to be displayed and allow interaction while the full size image loads.
*/
public final void setImage(@NonNull ImageSource imageSource, ImageSource previewSource) {
setImage(imageSource, previewSource, null);
}
/**
* Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be
* displayed until the full size image is loaded, starting with a given orientation setting, scale and center.
* This is the best method to use when you want scale and center to be restored after screen orientation change;
* it avoids any redundant loading of tiles in the wrong orientation.
*
* You must declare the dimensions of the full size image by calling {@link ImageSource#dimensions(int, int)}
* on the imageSource object. The preview source will be ignored if you don't provide dimensions,
* and if you provide a bitmap for the full size image.
* @param imageSource Image source. Dimensions must be declared.
* @param previewSource Optional source for a preview image to be displayed and allow interaction while the full size image loads.
* @param state State to be restored. Nullable.
*/
public final void setImage(@NonNull ImageSource imageSource, ImageSource previewSource, ImageViewState state) {
//noinspection ConstantConditions
if (imageSource == null) {
throw new NullPointerException("imageSource must not be null");
}
reset(true);
if (state != null) { restoreState(state); }
if (previewSource != null) {
if (imageSource.getBitmap() != null) {
throw new IllegalArgumentException("Preview image cannot be used when a bitmap is provided for the main image");
}
if (imageSource.getSWidth() <= 0 || imageSource.getSHeight() <= 0) {
throw new IllegalArgumentException("Preview image cannot be used unless dimensions are provided for the main image");
}
this.sWidth = imageSource.getSWidth();
this.sHeight = imageSource.getSHeight();
this.pRegion = previewSource.getSRegion();
if (previewSource.getBitmap() != null) {
this.bitmapIsCached = previewSource.isCached();
onPreviewLoaded(previewSource.getBitmap());
} else {
Uri uri = previewSource.getUri();
if (uri == null && previewSource.getResource() != null) {
uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + previewSource.getResource());
}
BitmapLoadTask task = new BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, true);
execute(task);
}
}
if (imageSource.getBitmap() != null && imageSource.getSRegion() != null) {
onImageLoaded(Bitmap.createBitmap(imageSource.getBitmap(), imageSource.getSRegion().left, imageSource.getSRegion().top, imageSource.getSRegion().width(), imageSource.getSRegion().height()), ORIENTATION_0, false);
} else if (imageSource.getBitmap() != null) {
onImageLoaded(imageSource.getBitmap(), ORIENTATION_0, imageSource.isCached());
} else {
sRegion = imageSource.getSRegion();
uri = imageSource.getUri();
if (uri == null && imageSource.getResource() != null) {
uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + imageSource.getResource());
}
if (imageSource.getTile() || sRegion != null) {
// Load the bitmap using tile decoding.
TilesInitTask task = new TilesInitTask(this, getContext(), regionDecoderFactory, uri);
execute(task);
} else {
// Load the bitmap as a single image.
BitmapLoadTask task = new BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, false);
execute(task);
}
}
}
/**
* Reset all state before setting/changing image or setting new rotation.
*/
private void reset(boolean newImage) {
debug("reset newImage=" + newImage);
scale = 0f;
scaleStart = 0f;
vTranslate = null;
vTranslateStart = null;
vTranslateBefore = null;
pendingScale = 0f;
sPendingCenter = null;
sRequestedCenter = null;
isZooming = false;
isPanning = false;
isQuickScaling = false;
maxTouchCount = 0;
fullImageSampleSize = 0;
vCenterStart = null;
vDistStart = 0;
quickScaleLastDistance = 0f;
quickScaleMoved = false;
quickScaleSCenter = null;
quickScaleVLastPoint = null;
quickScaleVStart = null;
anim = null;
satTemp = null;
matrix = null;
sRect = null;
if (newImage) {
uri = null;
decoderLock.writeLock().lock();
try {
if (decoder != null) {
decoder.recycle();
decoder = null;
}
} finally {
decoderLock.writeLock().unlock();
}
if (bitmap != null && !bitmapIsCached) {
bitmap.recycle();
}
if (bitmap != null && bitmapIsCached && onImageEventListener != null) {
onImageEventListener.onPreviewReleased();
}
sWidth = 0;
sHeight = 0;
sOrientation = 0;
sRegion = null;
pRegion = null;
readySent = false;
imageLoadedSent = false;
bitmap = null;
bitmapIsPreview = false;
bitmapIsCached = false;
}
if (tileMap != null) {
for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
for (Tile tile : tileMapEntry.getValue()) {
tile.visible = false;
if (tile.bitmap != null) {
tile.bitmap.recycle();
tile.bitmap = null;
}
}
}
tileMap = null;
}
setGestureDetector(getContext());
}
private void setGestureDetector(final Context context) {
this.detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
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) {
PointF vTranslateEnd = new PointF(vTranslate.x + (velocityX * 0.25f), vTranslate.y + (velocityY * 0.25f));
float sCenterXEnd = ((getWidth()/2) - vTranslateEnd.x)/scale;
float sCenterYEnd = ((getHeight()/2) - vTranslateEnd.y)/scale;
new AnimationBuilder(new PointF(sCenterXEnd, sCenterYEnd)).withEasing(EASE_OUT_QUAD).withPanLimited(false).withOrigin(ORIGIN_FLING).start();
return true;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
performClick();
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
if (zoomEnabled && readySent && vTranslate != null) {
// Hacky solution for #15 - after a double tap the GestureDetector gets in a state
// where the next fling is ignored, so here we replace it with a new one.
setGestureDetector(context);
if (quickScaleEnabled) {
// Store quick scale params. This will become either a double tap zoom or a
// quick scale depending on whether the user swipes.
vCenterStart = new PointF(e.getX(), e.getY());
vTranslateStart = new PointF(vTranslate.x, vTranslate.y);
scaleStart = scale;
isQuickScaling = true;
isZooming = true;
quickScaleLastDistance = -1F;
quickScaleSCenter = viewToSourceCoord(vCenterStart);
quickScaleVStart = new PointF(e.getX(), e.getY());
quickScaleVLastPoint = new PointF(quickScaleSCenter.x, quickScaleSCenter.y);
quickScaleMoved = false;
// We need to get events in onTouchEvent after this.
return false;
} else {
// Start double tap zoom animation.
doubleTapZoom(viewToSourceCoord(new PointF(e.getX(), e.getY())), new PointF(e.getX(), e.getY()));
return true;
}
}
return super.onDoubleTapEvent(e);
}
});
singleDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
performClick();
return true;
}
});
}
/**
* On resize, preserve center and scale. Various behaviours are possible, override this method to use another.
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
debug("onSizeChanged %dx%d -> %dx%d", oldw, oldh, w, h);
PointF sCenter = getCenter();
if (readySent && sCenter != null) {
this.anim = null;
this.pendingScale = scale;
this.sPendingCenter = sCenter;
}
}
/**
* Measures the width and height of the view, preserving the aspect ratio of the image displayed if wrap_content is
* used. The image will scale within this box, not resizing the view as it is zoomed.
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
int width = parentWidth;
int height = parentHeight;
if (sWidth > 0 && sHeight > 0) {
if (resizeWidth && resizeHeight) {
width = sWidth();
height = sHeight();
} else if (resizeHeight) {
height = (int)((((double)sHeight()/(double)sWidth()) * width));
} else if (resizeWidth) {
width = (int)((((double)sWidth()/(double)sHeight()) * height));
}
}
width = Math.max(width, getSuggestedMinimumWidth());
height = Math.max(height, getSuggestedMinimumHeight());
setMeasuredDimension(width, height);
}
/**
* Handle touch events. One finger pans, and two finger pinch and zoom plus panning.
*/
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
// During non-interruptible anims, ignore all touch events
if (anim != null && !anim.interruptible) {
requestDisallowInterceptTouchEvent(true);
return true;
} else {
if (anim != null && anim.listener != null) {
try {
anim.listener.onInterruptedByUser();
} catch (Exception e) {
Log.w(TAG, "Error thrown by animation listener", e);
}
}
anim = null;
}
// Abort if not ready
if (vTranslate == null) {
if (singleDetector != null) {
singleDetector.onTouchEvent(event);
}
return true;
}
// Detect flings, taps and double taps
if (!isQuickScaling && (detector == null || detector.onTouchEvent(event))) {
isZooming = false;
isPanning = false;
maxTouchCount = 0;
return true;
}
if (vTranslateStart == null) { vTranslateStart = new PointF(0, 0); }
if (vTranslateBefore == null) { vTranslateBefore = new PointF(0, 0); }
if (vCenterStart == null) { vCenterStart = new PointF(0, 0); }
// Store current values so we can send an event if they change
float scaleBefore = scale;
vTranslateBefore.set(vTranslate);
boolean handled = onTouchEventInternal(event);
sendStateChanged(scaleBefore, vTranslateBefore, ORIGIN_TOUCH);
return handled || super.onTouchEvent(event);
}
@SuppressWarnings("deprecation")
private boolean onTouchEventInternal(@NonNull MotionEvent event) {
int touchCount = event.getPointerCount();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_1_DOWN:
case MotionEvent.ACTION_POINTER_2_DOWN:
anim = null;
requestDisallowInterceptTouchEvent(true);
maxTouchCount = Math.max(maxTouchCount, touchCount);
if (touchCount >= 2) {
if (zoomEnabled) {
// Start pinch to zoom. Calculate distance between touch points and center point of the pinch.
float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1));
scaleStart = scale;
vDistStart = distance;
vTranslateStart.set(vTranslate.x, vTranslate.y);
vCenterStart.set((event.getX(0) + event.getX(1))/2, (event.getY(0) + event.getY(1))/2);
} else {
// Abort all gestures on second touch
maxTouchCount = 0;
}
// Cancel long click timer
handler.removeMessages(MESSAGE_LONG_CLICK);
} else if (!isQuickScaling) {
// Start one-finger pan
vTranslateStart.set(vTranslate.x, vTranslate.y);
vCenterStart.set(event.getX(), event.getY());
// Start long click timer
handler.sendEmptyMessageDelayed(MESSAGE_LONG_CLICK, 600);
}
return true;
case MotionEvent.ACTION_MOVE:
boolean consumed = false;
if (maxTouchCount > 0) {
if (touchCount >= 2) {
// Calculate new distance between touch points, to scale and pan relative to start values.
float vDistEnd = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1));
float vCenterEndX = (event.getX(0) + event.getX(1))/2;
float vCenterEndY = (event.getY(0) + event.getY(1))/2;
if (zoomEnabled && (distance(vCenterStart.x, vCenterEndX, vCenterStart.y, vCenterEndY) > 5 || Math.abs(vDistEnd - vDistStart) > 5 || isPanning)) {
isZooming = true;
isPanning = true;
consumed = true;
double previousScale = scale;
scale = Math.min(maxScale, (vDistEnd / vDistStart) * scaleStart);
if (scale <= minScale()) {
// Minimum scale reached so don't pan. Adjust start settings so any expand will zoom in.
vDistStart = vDistEnd;
scaleStart = minScale();
vCenterStart.set(vCenterEndX, vCenterEndY);
vTranslateStart.set(vTranslate);
} else if (panEnabled) {
// Translate to place the source image coordinate that was at the center of the pinch at the start
// at the center of the pinch now, to give simultaneous pan + zoom.
float vLeftStart = vCenterStart.x - vTranslateStart.x;
float vTopStart = vCenterStart.y - vTranslateStart.y;
float vLeftNow = vLeftStart * (scale/scaleStart);
float vTopNow = vTopStart * (scale/scaleStart);
vTranslate.x = vCenterEndX - vLeftNow;
vTranslate.y = vCenterEndY - vTopNow;
if ((previousScale * sHeight() < getHeight() && scale * sHeight() >= getHeight()) || (previousScale * sWidth() < getWidth() && scale * sWidth() >= getWidth())) {
fitToBounds(true);
vCenterStart.set(vCenterEndX, vCenterEndY);
vTranslateStart.set(vTranslate);
scaleStart = scale;
vDistStart = vDistEnd;
}
} else if (sRequestedCenter != null) {
// With a center specified from code, zoom around that point.
vTranslate.x = (getWidth()/2) - (scale * sRequestedCenter.x);
vTranslate.y = (getHeight()/2) - (scale * sRequestedCenter.y);
} else {
// With no requested center, scale around the image center.
vTranslate.x = (getWidth()/2) - (scale * (sWidth()/2));
vTranslate.y = (getHeight()/2) - (scale * (sHeight()/2));
}
fitToBounds(true);
refreshRequiredTiles(eagerLoadingEnabled);
}
} else if (isQuickScaling) {
// One finger zoom
// Stole Google's Magical Formula™ to make sure it feels the exact same
float dist = Math.abs(quickScaleVStart.y - event.getY()) * 2 + quickScaleThreshold;
if (quickScaleLastDistance == -1f) {
quickScaleLastDistance = dist;
}
boolean isUpwards = event.getY() > quickScaleVLastPoint.y;
quickScaleVLastPoint.set(0, event.getY());
float spanDiff = Math.abs(1 - (dist / quickScaleLastDistance)) * 0.5f;
if (spanDiff > 0.03f || quickScaleMoved) {
quickScaleMoved = true;
float multiplier = 1;
if (quickScaleLastDistance > 0) {
multiplier = isUpwards ? (1 + spanDiff) : (1 - spanDiff);
}
double previousScale = scale;
scale = Math.max(minScale(), Math.min(maxScale, scale * multiplier));
if (panEnabled) {
float vLeftStart = vCenterStart.x - vTranslateStart.x;
float vTopStart = vCenterStart.y - vTranslateStart.y;
float vLeftNow = vLeftStart * (scale/scaleStart);
float vTopNow = vTopStart * (scale/scaleStart);
vTranslate.x = vCenterStart.x - vLeftNow;
vTranslate.y = vCenterStart.y - vTopNow;
if ((previousScale * sHeight() < getHeight() && scale * sHeight() >= getHeight()) || (previousScale * sWidth() < getWidth() && scale * sWidth() >= getWidth())) {
fitToBounds(true);
vCenterStart.set(sourceToViewCoord(quickScaleSCenter));
vTranslateStart.set(vTranslate);
scaleStart = scale;
dist = 0;
}
} else if (sRequestedCenter != null) {
// With a center specified from code, zoom around that point.
vTranslate.x = (getWidth()/2) - (scale * sRequestedCenter.x);
vTranslate.y = (getHeight()/2) - (scale * sRequestedCenter.y);
} else {
// With no requested center, scale around the image center.
vTranslate.x = (getWidth()/2) - (scale * (sWidth()/2));
vTranslate.y = (getHeight()/2) - (scale * (sHeight()/2));
}
}
quickScaleLastDistance = dist;
fitToBounds(true);
refreshRequiredTiles(eagerLoadingEnabled);
consumed = true;
} else if (!isZooming) {
// One finger pan - translate the image. We do this calculation even with pan disabled so click
// and long click behaviour is preserved.
float dx = Math.abs(event.getX() - vCenterStart.x);
float dy = Math.abs(event.getY() - vCenterStart.y);
//On the Samsung S6 long click event does not work, because the dx > 5 usually true
float offset = density * 5;
if (dx > offset || dy > offset || isPanning) {
consumed = true;
vTranslate.x = vTranslateStart.x + (event.getX() - vCenterStart.x);
vTranslate.y = vTranslateStart.y + (event.getY() - vCenterStart.y);
float lastX = vTranslate.x;
float lastY = vTranslate.y;
fitToBounds(true);
boolean atXEdge = lastX != vTranslate.x;
boolean atYEdge = lastY != vTranslate.y;
boolean edgeXSwipe = atXEdge && dx > dy && !isPanning;
boolean edgeYSwipe = atYEdge && dy > dx && !isPanning;
boolean yPan = lastY == vTranslate.y && dy > offset * 3;
if (!edgeXSwipe && !edgeYSwipe && (!atXEdge || !atYEdge || yPan || isPanning)) {
isPanning = true;
} else if (dx > offset || dy > offset) {
// Haven't panned the image, and we're at the left or right edge. Switch to page swipe.
maxTouchCount = 0;
handler.removeMessages(MESSAGE_LONG_CLICK);
requestDisallowInterceptTouchEvent(false);
}
if (!panEnabled) {
vTranslate.x = vTranslateStart.x;
vTranslate.y = vTranslateStart.y;
requestDisallowInterceptTouchEvent(false);
}
refreshRequiredTiles(eagerLoadingEnabled);
}
}
}
if (consumed) {
handler.removeMessages(MESSAGE_LONG_CLICK);
invalidate();
return true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_POINTER_2_UP:
handler.removeMessages(MESSAGE_LONG_CLICK);
if (isQuickScaling) {
isQuickScaling = false;
if (!quickScaleMoved) {
doubleTapZoom(quickScaleSCenter, vCenterStart);
}
}
if (maxTouchCount > 0 && (isZooming || isPanning)) {
if (isZooming && touchCount == 2) {
// Convert from zoom to pan with remaining touch
isPanning = true;
vTranslateStart.set(vTranslate.x, vTranslate.y);
if (event.getActionIndex() == 1) {
vCenterStart.set(event.getX(0), event.getY(0));
} else {
vCenterStart.set(event.getX(1), event.getY(1));
}
}
if (touchCount < 3) {
// End zooming when only one touch point
isZooming = false;
}
if (touchCount < 2) {
// End panning when no touch points
isPanning = false;
maxTouchCount = 0;
}
// Trigger load of tiles now required
refreshRequiredTiles(true);
return true;
}
if (touchCount == 1) {
isZooming = false;
isPanning = false;
maxTouchCount = 0;
}
return true;
}
return false;
}
private void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
/**
* Double tap zoom handler triggered from gesture detector or on touch, depending on whether
* quick scale is enabled.
*/
private void doubleTapZoom(PointF sCenter, PointF vFocus) {
if (!panEnabled) {
if (sRequestedCenter != null) {
// With a center specified from code, zoom around that point.
sCenter.x = sRequestedCenter.x;
sCenter.y = sRequestedCenter.y;
} else {
// With no requested center, scale around the image center.
sCenter.x = sWidth()/2;
sCenter.y = sHeight()/2;
}
}
float doubleTapZoomScale = Math.min(maxScale, SubsamplingScaleImageView.this.doubleTapZoomScale);
boolean zoomIn = (scale <= doubleTapZoomScale * 0.9) || scale == minScale;
float targetScale = zoomIn ? doubleTapZoomScale : minScale();
if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER_IMMEDIATE) {
setScaleAndCenter(targetScale, sCenter);
} else if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER || !zoomIn || !panEnabled) {
new AnimationBuilder(targetScale, sCenter).withInterruptible(false).withDuration(doubleTapZoomDuration).withOrigin(ORIGIN_DOUBLE_TAP_ZOOM).start();
} else if (doubleTapZoomStyle == ZOOM_FOCUS_FIXED) {
new AnimationBuilder(targetScale, sCenter, vFocus).withInterruptible(false).withDuration(doubleTapZoomDuration).withOrigin(ORIGIN_DOUBLE_TAP_ZOOM).start();
}
invalidate();
}
/**
* Draw method should not be called until the view has dimensions so the first calls are used as triggers to calculate
* the scaling and tiling required. Once the view is setup, tiles are displayed as they are loaded.
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
createPaints();
// If image or view dimensions are not known yet, abort.
if (sWidth == 0 || sHeight == 0 || getWidth() == 0 || getHeight() == 0) {
return;
}
// When using tiles, on first render with no tile map ready, initialise it and kick off async base image loading.
if (tileMap == null && decoder != null) {
initialiseBaseLayer(getMaxBitmapDimensions(canvas));
}
// If image has been loaded or supplied as a bitmap, onDraw may be the first time the view has
// dimensions and therefore the first opportunity to set scale and translate. If this call returns
// false there is nothing to be drawn so return immediately.
if (!checkReady()) {
return;
}
// Set scale and translate before draw.
preDraw();
// If animating scale, calculate current scale and center with easing equations
if (anim != null && anim.vFocusStart != null) {
// Store current values so we can send an event if they change
float scaleBefore = scale;
if (vTranslateBefore == null) { vTranslateBefore = new PointF(0, 0); }
vTranslateBefore.set(vTranslate);
long scaleElapsed = System.currentTimeMillis() - anim.time;
boolean finished = scaleElapsed > anim.duration;
scaleElapsed = Math.min(scaleElapsed, anim.duration);
scale = ease(anim.easing, scaleElapsed, anim.scaleStart, anim.scaleEnd - anim.scaleStart, anim.duration);
// Apply required animation to the focal point
float vFocusNowX = ease(anim.easing, scaleElapsed, anim.vFocusStart.x, anim.vFocusEnd.x - anim.vFocusStart.x, anim.duration);
float vFocusNowY = ease(anim.easing, scaleElapsed, anim.vFocusStart.y, anim.vFocusEnd.y - anim.vFocusStart.y, anim.duration);
// Find out where the focal point is at this scale and adjust its position to follow the animation path
vTranslate.x -= sourceToViewX(anim.sCenterEnd.x) - vFocusNowX;
vTranslate.y -= sourceToViewY(anim.sCenterEnd.y) - vFocusNowY;
// For translate anims, showing the image non-centered is never allowed, for scaling anims it is during the animation.
fitToBounds(finished || (anim.scaleStart == anim.scaleEnd));
sendStateChanged(scaleBefore, vTranslateBefore, anim.origin);
refreshRequiredTiles(finished);
if (finished) {
if (anim.listener != null) {
try {
anim.listener.onComplete();
} catch (Exception e) {
Log.w(TAG, "Error thrown by animation listener", e);
}
}
anim = null;
}
invalidate();
}
if (tileMap != null && isBaseLayerReady()) {
// Optimum sample size for current scale
int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize(scale));
// First check for missing tiles - if there are any we need the base layer underneath to avoid gaps
boolean hasMissingTiles = false;
for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
if (tileMapEntry.getKey() == sampleSize) {
for (Tile tile : tileMapEntry.getValue()) {
if (tile.visible && (tile.loading || tile.bitmap == null)) {
hasMissingTiles = true;
}
}
}
}
// Render all loaded tiles. LinkedHashMap used for bottom up rendering - lower res tiles underneath.
for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
if (tileMapEntry.getKey() == sampleSize || hasMissingTiles) {
for (Tile tile : tileMapEntry.getValue()) {
sourceToViewRect(tile.sRect, tile.vRect);
if (!tile.loading && tile.bitmap != null) {
if (tileBgPaint != null) {
canvas.drawRect(tile.vRect, tileBgPaint);
}
if (matrix == null) { matrix = new Matrix(); }
matrix.reset();
setMatrixArray(srcArray, 0, 0, tile.bitmap.getWidth(), 0, tile.bitmap.getWidth(), tile.bitmap.getHeight(), 0, tile.bitmap.getHeight());
if (getRequiredRotation() == ORIENTATION_0) {
setMatrixArray(dstArray, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom);
} else if (getRequiredRotation() == ORIENTATION_90) {
setMatrixArray(dstArray, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top);
} else if (getRequiredRotation() == ORIENTATION_180) {
setMatrixArray(dstArray, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top);
} else if (getRequiredRotation() == ORIENTATION_270) {
setMatrixArray(dstArray, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom);
}
matrix.setPolyToPoly(srcArray, 0, dstArray, 0, 4);
canvas.drawBitmap(tile.bitmap, matrix, bitmapPaint);
if (debug) {
canvas.drawRect(tile.vRect, debugLinePaint);
}
} else if (tile.loading && debug) {
canvas.drawText("LOADING", tile.vRect.left + px(5), tile.vRect.top + px(35), debugTextPaint);
}
if (tile.visible && debug) {
canvas.drawText("ISS " + tile.sampleSize + " RECT " + tile.sRect.top + "," + tile.sRect.left + "," + tile.sRect.bottom + "," + tile.sRect.right, tile.vRect.left + px(5), tile.vRect.top + px(15), debugTextPaint);
}
}
}
}
} else if (bitmap != null && !bitmap.isRecycled()) {
float xScale = scale, yScale = scale;
if (bitmapIsPreview) {
xScale = scale * ((float)sWidth/bitmap.getWidth());
yScale = scale * ((float)sHeight/bitmap.getHeight());
}
if (matrix == null) { matrix = new Matrix(); }
matrix.reset();
matrix.postScale(xScale, yScale);
matrix.postRotate(getRequiredRotation());
matrix.postTranslate(vTranslate.x, vTranslate.y);
if (getRequiredRotation() == ORIENTATION_180) {
matrix.postTranslate(scale * sWidth, scale * sHeight);
} else if (getRequiredRotation() == ORIENTATION_90) {
matrix.postTranslate(scale * sHeight, 0);
} else if (getRequiredRotation() == ORIENTATION_270) {
matrix.postTranslate(0, scale * sWidth);
}
if (tileBgPaint != null) {
if (sRect == null) { sRect = new RectF(); }
sRect.set(0f, 0f, bitmapIsPreview ? bitmap.getWidth() : sWidth, bitmapIsPreview ? bitmap.getHeight() : sHeight);
matrix.mapRect(sRect);
canvas.drawRect(sRect, tileBgPaint);
}
canvas.drawBitmap(bitmap, matrix, bitmapPaint);
}
if (debug) {
canvas.drawText("Scale: " + String.format(Locale.ENGLISH, "%.2f", scale) + " (" + String.format(Locale.ENGLISH, "%.2f", minScale()) + " - " + String.format(Locale.ENGLISH, "%.2f", maxScale) + ")", px(5), px(15), debugTextPaint);
canvas.drawText("Translate: " + String.format(Locale.ENGLISH, "%.2f", vTranslate.x) + ":" + String.format(Locale.ENGLISH, "%.2f", vTranslate.y), px(5), px(30), debugTextPaint);
PointF center = getCenter();
//noinspection ConstantConditions
canvas.drawText("Source center: " + String.format(Locale.ENGLISH, "%.2f", center.x) + ":" + String.format(Locale.ENGLISH, "%.2f", center.y), px(5), px(45), debugTextPaint);
if (anim != null) {
PointF vCenterStart = sourceToViewCoord(anim.sCenterStart);
PointF vCenterEndRequested = sourceToViewCoord(anim.sCenterEndRequested);
PointF vCenterEnd = sourceToViewCoord(anim.sCenterEnd);
//noinspection ConstantConditions
canvas.drawCircle(vCenterStart.x, vCenterStart.y, px(10), debugLinePaint);
debugLinePaint.setColor(Color.RED);
//noinspection ConstantConditions
canvas.drawCircle(vCenterEndRequested.x, vCenterEndRequested.y, px(20), debugLinePaint);
debugLinePaint.setColor(Color.BLUE);
//noinspection ConstantConditions
canvas.drawCircle(vCenterEnd.x, vCenterEnd.y, px(25), debugLinePaint);
debugLinePaint.setColor(Color.CYAN);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, px(30), debugLinePaint);
}
if (vCenterStart != null) {
debugLinePaint.setColor(Color.RED);
canvas.drawCircle(vCenterStart.x, vCenterStart.y, px(20), debugLinePaint);
}
if (quickScaleSCenter != null) {
debugLinePaint.setColor(Color.BLUE);
canvas.drawCircle(sourceToViewX(quickScaleSCenter.x), sourceToViewY(quickScaleSCenter.y), px(35), debugLinePaint);
}
if (quickScaleVStart != null && isQuickScaling) {
debugLinePaint.setColor(Color.CYAN);
canvas.drawCircle(quickScaleVStart.x, quickScaleVStart.y, px(30), debugLinePaint);
}
debugLinePaint.setColor(Color.MAGENTA);
}
}
/**
* Helper method for setting the values of a tile matrix array.
*/
private void setMatrixArray(float[] array, float f0, float f1, float f2, float f3, float f4, float f5, float f6, float f7) {
array[0] = f0;
array[1] = f1;
array[2] = f2;
array[3] = f3;
array[4] = f4;
array[5] = f5;
array[6] = f6;
array[7] = f7;
}
/**
* Checks whether the base layer of tiles or full size bitmap is ready.
*/
private boolean isBaseLayerReady() {
if (bitmap != null && !bitmapIsPreview) {
return true;
} else if (tileMap != null) {
boolean baseLayerReady = true;
for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
if (tileMapEntry.getKey() == fullImageSampleSize) {
for (Tile tile : tileMapEntry.getValue()) {
if (tile.loading || tile.bitmap == null) {
baseLayerReady = false;
}
}
}
}
return baseLayerReady;
}
return false;
}
/**
* Check whether view and image dimensions are known and either a preview, full size image or
* base layer tiles are loaded. First time, send ready event to listener. The next draw will
* display an image.
*/
private boolean checkReady() {
boolean ready = getWidth() > 0 && getHeight() > 0 && sWidth > 0 && sHeight > 0 && (bitmap != null || isBaseLayerReady());
if (!readySent && ready) {
preDraw();
readySent = true;
onReady();
if (onImageEventListener != null) {
onImageEventListener.onReady();
}
}
return ready;
}
/**
* Check whether either the full size bitmap or base layer tiles are loaded. First time, send image
* loaded event to listener.
*/
private boolean checkImageLoaded() {
boolean imageLoaded = isBaseLayerReady();
if (!imageLoadedSent && imageLoaded) {
preDraw();
imageLoadedSent = true;
onImageLoaded();
if (onImageEventListener != null) {
onImageEventListener.onImageLoaded();
}
}
return imageLoaded;
}
/**
* Creates Paint objects once when first needed.
*/
private void createPaints() {
if (bitmapPaint == null) {
bitmapPaint = new Paint();
bitmapPaint.setAntiAlias(true);
bitmapPaint.setFilterBitmap(true);
bitmapPaint.setDither(true);
}
if ((debugTextPaint == null || debugLinePaint == null) && debug) {
debugTextPaint = new Paint();
debugTextPaint.setTextSize(px(12));
debugTextPaint.setColor(Color.MAGENTA);
debugTextPaint.setStyle(Style.FILL);
debugLinePaint = new Paint();
debugLinePaint.setColor(Color.MAGENTA);
debugLinePaint.setStyle(Style.STROKE);
debugLinePaint.setStrokeWidth(px(1));
}
}
/**
* Called on first draw when the view has dimensions. Calculates the initial sample size and starts async loading of
* the base layer image - the whole source subsampled as necessary.
*/
private synchronized void initialiseBaseLayer(@NonNull Point maxTileDimensions) {
debug("initialiseBaseLayer maxTileDimensions=%dx%d", maxTileDimensions.x, maxTileDimensions.y);
satTemp = new ScaleAndTranslate(0f, new PointF(0, 0));
fitToBounds(true, satTemp);
// Load double resolution - next level will be split into four tiles and at the center all four are required,
// so don't bother with tiling until the next level 16 tiles are needed.
fullImageSampleSize = calculateInSampleSize(satTemp.scale);
if (fullImageSampleSize > 1) {
fullImageSampleSize /= 2;
}
if (fullImageSampleSize == 1 && sRegion == null && sWidth() < maxTileDimensions.x && sHeight() < maxTileDimensions.y) {
// Whole image is required at native resolution, and is smaller than the canvas max bitmap size.
// Use BitmapDecoder for better image support.
decoder.recycle();
decoder = null;
BitmapLoadTask task = new BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, false);
execute(task);
} else {
initialiseTileMap(maxTileDimensions);
List baseGrid = tileMap.get(fullImageSampleSize);
for (Tile baseTile : baseGrid) {
TileLoadTask task = new TileLoadTask(this, decoder, baseTile);
execute(task);
}
refreshRequiredTiles(true);
}
}
/**
* Loads the optimum tiles for display at the current scale and translate, so the screen can be filled with tiles
* that are at least as high resolution as the screen. Frees up bitmaps that are now off the screen.
* @param load Whether to load the new tiles needed. Use false while scrolling/panning for performance.
*/
private void refreshRequiredTiles(boolean load) {
if (decoder == null || tileMap == null) { return; }
int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize(scale));
// Load tiles of the correct sample size that are on screen. Discard tiles off screen, and those that are higher
// resolution than required, or lower res than required but not the base layer, so the base layer is always present.
for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
for (Tile tile : tileMapEntry.getValue()) {
if (tile.sampleSize < sampleSize || (tile.sampleSize > sampleSize && tile.sampleSize != fullImageSampleSize)) {
tile.visible = false;
if (tile.bitmap != null) {
tile.bitmap.recycle();
tile.bitmap = null;
}
}
if (tile.sampleSize == sampleSize) {
if (tileVisible(tile)) {
tile.visible = true;
if (!tile.loading && tile.bitmap == null && load) {
TileLoadTask task = new TileLoadTask(this, decoder, tile);
execute(task);
}
} else if (tile.sampleSize != fullImageSampleSize) {
tile.visible = false;
if (tile.bitmap != null) {
tile.bitmap.recycle();
tile.bitmap = null;
}
}
} else if (tile.sampleSize == fullImageSampleSize) {
tile.visible = true;
}
}
}
}
/**
* Determine whether tile is visible.
*/
private boolean tileVisible(Tile tile) {
float sVisLeft = viewToSourceX(0),
sVisRight = viewToSourceX(getWidth()),
sVisTop = viewToSourceY(0),
sVisBottom = viewToSourceY(getHeight());
return !(sVisLeft > tile.sRect.right || tile.sRect.left > sVisRight || sVisTop > tile.sRect.bottom || tile.sRect.top > sVisBottom);
}
/**
* Sets scale and translate ready for the next draw.
*/
private void preDraw() {
if (getWidth() == 0 || getHeight() == 0 || sWidth <= 0 || sHeight <= 0) {
return;
}
// If waiting to translate to new center position, set translate now
if (sPendingCenter != null && pendingScale != null) {
scale = pendingScale;
if (vTranslate == null) {
vTranslate = new PointF();
}
vTranslate.x = (getWidth()/2) - (scale * sPendingCenter.x);
vTranslate.y = (getHeight()/2) - (scale * sPendingCenter.y);
sPendingCenter = null;
pendingScale = null;
fitToBounds(true);
refreshRequiredTiles(true);
}
// On first display of base image set up position, and in other cases make sure scale is correct.
fitToBounds(false);
}
/**
* Calculates sample size to fit the source image in given bounds.
*/
private int calculateInSampleSize(float scale) {
if (minimumTileDpi > 0) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float averageDpi = (metrics.xdpi + metrics.ydpi)/2;
scale = (minimumTileDpi/averageDpi) * scale;
}
int reqWidth = (int)(sWidth() * scale);
int reqHeight = (int)(sHeight() * scale);
// Raw height and width of image
int inSampleSize = 1;
if (reqWidth == 0 || reqHeight == 0) {
return 32;
}
if (sHeight() > reqHeight || sWidth() > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) sHeight() / (float) reqHeight);
final int widthRatio = Math.round((float) sWidth() / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
// We want the actual sample size that will be used, so round down to nearest power of 2.
int power = 1;
while (power * 2 < inSampleSize) {
power = power * 2;
}
return power;
}
/**
* Adjusts hypothetical future scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale
* 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
* animation should be.
* @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.
* @param sat The scale we want and the translation we're aiming for. The values are adjusted to be valid.
*/
private void fitToBounds(boolean center, ScaleAndTranslate sat) {
if (panLimit == PAN_LIMIT_OUTSIDE && isReady()) {
center = false;
}
PointF vTranslate = sat.vTranslate;
float scale = limitedScale(sat.scale);
float scaleWidth = scale * sWidth();
float scaleHeight = scale * sHeight();
if (panLimit == PAN_LIMIT_CENTER && isReady()) {
vTranslate.x = Math.max(vTranslate.x, getWidth()/2 - scaleWidth);
vTranslate.y = Math.max(vTranslate.y, getHeight()/2 - scaleHeight);
} else if (center) {
vTranslate.x = Math.max(vTranslate.x, getWidth() - scaleWidth);
vTranslate.y = Math.max(vTranslate.y, getHeight() - scaleHeight);
} else {
vTranslate.x = Math.max(vTranslate.x, -scaleWidth);
vTranslate.y = Math.max(vTranslate.y, -scaleHeight);
}
// Asymmetric padding adjustments
float xPaddingRatio = getPaddingLeft() > 0 || getPaddingRight() > 0 ? getPaddingLeft()/(float)(getPaddingLeft() + getPaddingRight()) : 0.5f;
float yPaddingRatio = getPaddingTop() > 0 || getPaddingBottom() > 0 ? getPaddingTop()/(float)(getPaddingTop() + getPaddingBottom()) : 0.5f;
float maxTx;
float maxTy;
if (panLimit == PAN_LIMIT_CENTER && isReady()) {
maxTx = Math.max(0, getWidth()/2);
maxTy = Math.max(0, getHeight()/2);
} else if (center) {
maxTx = Math.max(0, (getWidth() - scaleWidth) * xPaddingRatio);
maxTy = Math.max(0, (getHeight() - scaleHeight) * yPaddingRatio);
} else {
maxTx = Math.max(0, getWidth());
maxTy = Math.max(0, getHeight());
}
vTranslate.x = Math.min(vTranslate.x, maxTx);
vTranslate.y = Math.min(vTranslate.y, maxTy);
sat.scale = scale;
}
/**
* Adjusts current scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale
* is set so one dimension fills the view and the image is centered on the other dimension.
* @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.
*/
private void fitToBounds(boolean center) {
boolean init = false;
if (vTranslate == null) {
init = true;
vTranslate = new PointF(0, 0);
}
if (satTemp == null) {
satTemp = new ScaleAndTranslate(0, new PointF(0, 0));
}
satTemp.scale = scale;
satTemp.vTranslate.set(vTranslate);
fitToBounds(center, satTemp);
scale = satTemp.scale;
vTranslate.set(satTemp.vTranslate);
if (init && minimumScaleType != SCALE_TYPE_START) {
vTranslate.set(vTranslateForSCenter(sWidth()/2, sHeight()/2, scale));
}
}
/**
* Once source image and view dimensions are known, creates a map of sample size to tile grid.
*/
private void initialiseTileMap(Point maxTileDimensions) {
debug("initialiseTileMap maxTileDimensions=%dx%d", maxTileDimensions.x, maxTileDimensions.y);
this.tileMap = new LinkedHashMap<>();
int sampleSize = fullImageSampleSize;
int xTiles = 1;
int yTiles = 1;
while (true) {
int sTileWidth = sWidth()/xTiles;
int sTileHeight = sHeight()/yTiles;
int subTileWidth = sTileWidth/sampleSize;
int subTileHeight = sTileHeight/sampleSize;
while (subTileWidth + xTiles + 1 > maxTileDimensions.x || (subTileWidth > getWidth() * 1.25 && sampleSize < fullImageSampleSize)) {
xTiles += 1;
sTileWidth = sWidth()/xTiles;
subTileWidth = sTileWidth/sampleSize;
}
while (subTileHeight + yTiles + 1 > maxTileDimensions.y || (subTileHeight > getHeight() * 1.25 && sampleSize < fullImageSampleSize)) {
yTiles += 1;
sTileHeight = sHeight()/yTiles;
subTileHeight = sTileHeight/sampleSize;
}
List tileGrid = new ArrayList<>(xTiles * yTiles);
for (int x = 0; x < xTiles; x++) {
for (int y = 0; y < yTiles; y++) {
Tile tile = new Tile();
tile.sampleSize = sampleSize;
tile.visible = sampleSize == fullImageSampleSize;
tile.sRect = new Rect(
x * sTileWidth,
y * sTileHeight,
x == xTiles - 1 ? sWidth() : (x + 1) * sTileWidth,
y == yTiles - 1 ? sHeight() : (y + 1) * sTileHeight
);
tile.vRect = new Rect(0, 0, 0, 0);
tile.fileSRect = new Rect(tile.sRect);
tileGrid.add(tile);
}
}
tileMap.put(sampleSize, tileGrid);
if (sampleSize == 1) {
break;
} else {
sampleSize /= 2;
}
}
}
/**
* Async task used to get image details without blocking the UI thread.
*/
private static class TilesInitTask extends AsyncTask {
private final WeakReference viewRef;
private final WeakReference contextRef;
private final WeakReference> decoderFactoryRef;
private final Uri source;
private ImageRegionDecoder decoder;
private Exception exception;
TilesInitTask(SubsamplingScaleImageView view, Context context, DecoderFactory extends ImageRegionDecoder> decoderFactory, Uri source) {
this.viewRef = new WeakReference<>(view);
this.contextRef = new WeakReference<>(context);
this.decoderFactoryRef = new WeakReference>(decoderFactory);
this.source = source;
}
@Override
protected int[] doInBackground(Void... params) {
try {
String sourceUri = source.toString();
Context context = contextRef.get();
DecoderFactory extends ImageRegionDecoder> decoderFactory = decoderFactoryRef.get();
SubsamplingScaleImageView view = viewRef.get();
if (context != null && decoderFactory != null && view != null) {
view.debug("TilesInitTask.doInBackground");
decoder = decoderFactory.make();
Point dimensions = decoder.init(context, source);
int sWidth = dimensions.x;
int sHeight = dimensions.y;
int exifOrientation = view.getExifOrientation(context, sourceUri);
if (view.sRegion != null) {
view.sRegion.left = Math.max(0, view.sRegion.left);
view.sRegion.top = Math.max(0, view.sRegion.top);
view.sRegion.right = Math.min(sWidth, view.sRegion.right);
view.sRegion.bottom = Math.min(sHeight, view.sRegion.bottom);
sWidth = view.sRegion.width();
sHeight = view.sRegion.height();
}
return new int[] { sWidth, sHeight, exifOrientation };
}
} catch (Exception e) {
Log.e(TAG, "Failed to initialise bitmap decoder", e);
this.exception = e;
}
return null;
}
@Override
protected void onPostExecute(int[] xyo) {
final SubsamplingScaleImageView view = viewRef.get();
if (view != null) {
if (decoder != null && xyo != null && xyo.length == 3) {
view.onTilesInited(decoder, xyo[0], xyo[1], xyo[2]);
} else if (exception != null && view.onImageEventListener != null) {
view.onImageEventListener.onImageLoadError(exception);
}
}
}
}
/**
* Called by worker task when decoder is ready and image size and EXIF orientation is known.
*/
private synchronized void onTilesInited(ImageRegionDecoder decoder, int sWidth, int sHeight, int sOrientation) {
debug("onTilesInited sWidth=%d, sHeight=%d, sOrientation=%d", sWidth, sHeight, orientation);
// If actual dimensions don't match the declared size, reset everything.
if (this.sWidth > 0 && this.sHeight > 0 && (this.sWidth != sWidth || this.sHeight != sHeight)) {
reset(false);
if (bitmap != null) {
if (!bitmapIsCached) {
bitmap.recycle();
}
bitmap = null;
if (onImageEventListener != null && bitmapIsCached) {
onImageEventListener.onPreviewReleased();
}
bitmapIsPreview = false;
bitmapIsCached = false;
}
}
this.decoder = decoder;
this.sWidth = sWidth;
this.sHeight = sHeight;
this.sOrientation = sOrientation;
checkReady();
if (!checkImageLoaded() && maxTileWidth > 0 && maxTileWidth != TILE_SIZE_AUTO && maxTileHeight > 0 && maxTileHeight != TILE_SIZE_AUTO && getWidth() > 0 && getHeight() > 0) {
initialiseBaseLayer(new Point(maxTileWidth, maxTileHeight));
}
invalidate();
requestLayout();
}
/**
* Async task used to load images without blocking the UI thread.
*/
private static class TileLoadTask extends AsyncTask {
private final WeakReference viewRef;
private final WeakReference decoderRef;
private final WeakReference tileRef;
private Exception exception;
TileLoadTask(SubsamplingScaleImageView view, ImageRegionDecoder decoder, Tile tile) {
this.viewRef = new WeakReference<>(view);
this.decoderRef = new WeakReference<>(decoder);
this.tileRef = new WeakReference<>(tile);
tile.loading = true;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
SubsamplingScaleImageView view = viewRef.get();
ImageRegionDecoder decoder = decoderRef.get();
Tile tile = tileRef.get();
if (decoder != null && tile != null && view != null && decoder.isReady() && tile.visible) {
view.debug("TileLoadTask.doInBackground, tile.sRect=%s, tile.sampleSize=%d", tile.sRect, tile.sampleSize);
view.decoderLock.readLock().lock();
try {
if (decoder.isReady()) {
// Update tile's file sRect according to rotation
view.fileSRect(tile.sRect, tile.fileSRect);
if (view.sRegion != null) {
tile.fileSRect.offset(view.sRegion.left, view.sRegion.top);
}
return decoder.decodeRegion(tile.fileSRect, tile.sampleSize);
} else {
tile.loading = false;
}
} finally {
view.decoderLock.readLock().unlock();
}
} else if (tile != null) {
tile.loading = false;
}
} catch (Exception e) {
Log.e(TAG, "Failed to decode tile", e);
this.exception = e;
} catch (OutOfMemoryError e) {
Log.e(TAG, "Failed to decode tile - OutOfMemoryError", e);
this.exception = new RuntimeException(e);
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
final SubsamplingScaleImageView subsamplingScaleImageView = viewRef.get();
final Tile tile = tileRef.get();
if (subsamplingScaleImageView != null && tile != null) {
if (bitmap != null) {
tile.bitmap = bitmap;
tile.loading = false;
subsamplingScaleImageView.onTileLoaded();
} else if (exception != null && subsamplingScaleImageView.onImageEventListener != null) {
subsamplingScaleImageView.onImageEventListener.onTileLoadError(exception);
}
}
}
}
/**
* Called by worker task when a tile has loaded. Redraws the view.
*/
private synchronized void onTileLoaded() {
debug("onTileLoaded");
checkReady();
checkImageLoaded();
if (isBaseLayerReady() && bitmap != null) {
if (!bitmapIsCached) {
bitmap.recycle();
}
bitmap = null;
if (onImageEventListener != null && bitmapIsCached) {
onImageEventListener.onPreviewReleased();
}
bitmapIsPreview = false;
bitmapIsCached = false;
}
invalidate();
}
/**
* Async task used to load bitmap without blocking the UI thread.
*/
private static class BitmapLoadTask extends AsyncTask {
private final WeakReference viewRef;
private final WeakReference contextRef;
private final WeakReference> decoderFactoryRef;
private final Uri source;
private final boolean preview;
private Bitmap bitmap;
private Exception exception;
BitmapLoadTask(SubsamplingScaleImageView view, Context context, DecoderFactory extends ImageDecoder> decoderFactory, Uri source, boolean preview) {
this.viewRef = new WeakReference<>(view);
this.contextRef = new WeakReference<>(context);
this.decoderFactoryRef = new WeakReference>(decoderFactory);
this.source = source;
this.preview = preview;
}
@Override
protected Integer doInBackground(Void... params) {
try {
String sourceUri = source.toString();
Context context = contextRef.get();
DecoderFactory extends ImageDecoder> decoderFactory = decoderFactoryRef.get();
SubsamplingScaleImageView view = viewRef.get();
if (context != null && decoderFactory != null && view != null) {
view.debug("BitmapLoadTask.doInBackground");
bitmap = decoderFactory.make().decode(context, source);
return view.getExifOrientation(context, sourceUri);
}
} catch (Exception e) {
Log.e(TAG, "Failed to load bitmap", e);
this.exception = e;
} catch (OutOfMemoryError e) {
Log.e(TAG, "Failed to load bitmap - OutOfMemoryError", e);
this.exception = new RuntimeException(e);
}
return null;
}
@Override
protected void onPostExecute(Integer orientation) {
SubsamplingScaleImageView subsamplingScaleImageView = viewRef.get();
if (subsamplingScaleImageView != null) {
if (bitmap != null && orientation != null) {
if (preview) {
subsamplingScaleImageView.onPreviewLoaded(bitmap);
} else {
subsamplingScaleImageView.onImageLoaded(bitmap, orientation, false);
}
} else if (exception != null && subsamplingScaleImageView.onImageEventListener != null) {
if (preview) {
subsamplingScaleImageView.onImageEventListener.onPreviewLoadError(exception);
} else {
subsamplingScaleImageView.onImageEventListener.onImageLoadError(exception);
}
}
}
}
}
/**
* Called by worker task when preview image is loaded.
*/
private synchronized void onPreviewLoaded(Bitmap previewBitmap) {
debug("onPreviewLoaded");
if (bitmap != null || imageLoadedSent) {
previewBitmap.recycle();
return;
}
if (pRegion != null) {
bitmap = Bitmap.createBitmap(previewBitmap, pRegion.left, pRegion.top, pRegion.width(), pRegion.height());
} else {
bitmap = previewBitmap;
}
bitmapIsPreview = true;
if (checkReady()) {
invalidate();
requestLayout();
}
}
/**
* Called by worker task when full size image bitmap is ready (tiling is disabled).
*/
private synchronized void onImageLoaded(Bitmap bitmap, int sOrientation, boolean bitmapIsCached) {
debug("onImageLoaded");
// If actual dimensions don't match the declared size, reset everything.
if (this.sWidth > 0 && this.sHeight > 0 && (this.sWidth != bitmap.getWidth() || this.sHeight != bitmap.getHeight())) {
reset(false);
}
if (this.bitmap != null && !this.bitmapIsCached) {
this.bitmap.recycle();
}
if (this.bitmap != null && this.bitmapIsCached && onImageEventListener!=null) {
onImageEventListener.onPreviewReleased();
}
this.bitmapIsPreview = false;
this.bitmapIsCached = bitmapIsCached;
this.bitmap = bitmap;
this.sWidth = bitmap.getWidth();
this.sHeight = bitmap.getHeight();
this.sOrientation = sOrientation;
boolean ready = checkReady();
boolean imageLoaded = checkImageLoaded();
if (ready || imageLoaded) {
invalidate();
requestLayout();
}
}
/**
* Helper method for load tasks. Examines the EXIF info on the image file to determine the orientation.
* This will only work for external files, not assets, resources or other URIs.
*/
@AnyThread
private int getExifOrientation(Context context, String sourceUri) {
int exifOrientation = ORIENTATION_0;
if (sourceUri.startsWith(ContentResolver.SCHEME_CONTENT)) {
Cursor cursor = null;
try {
String[] columns = { MediaStore.Images.Media.ORIENTATION };
cursor = context.getContentResolver().query(Uri.parse(sourceUri), columns, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int orientation = cursor.getInt(0);
if (VALID_ORIENTATIONS.contains(orientation) && orientation != ORIENTATION_USE_EXIF) {
exifOrientation = orientation;
} else {
Log.w(TAG, "Unsupported orientation: " + orientation);
}
}
}
} catch (Exception e) {
Log.w(TAG, "Could not get orientation of image from media store");
} finally {
if (cursor != null) {
cursor.close();
}
}
} else if (sourceUri.startsWith(ImageSource.FILE_SCHEME) && !sourceUri.startsWith(ImageSource.ASSET_SCHEME)) {
try {
ExifInterface exifInterface = new ExifInterface(sourceUri.substring(ImageSource.FILE_SCHEME.length() - 1));
int orientationAttr = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
if (orientationAttr == ExifInterface.ORIENTATION_NORMAL || orientationAttr == ExifInterface.ORIENTATION_UNDEFINED) {
exifOrientation = ORIENTATION_0;
} else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_90) {
exifOrientation = ORIENTATION_90;
} else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_180) {
exifOrientation = ORIENTATION_180;
} else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_270) {
exifOrientation = ORIENTATION_270;
} else {
Log.w(TAG, "Unsupported EXIF orientation: " + orientationAttr);
}
} catch (Exception e) {
Log.w(TAG, "Could not get EXIF orientation of image");
}
}
return exifOrientation;
}
private void execute(AsyncTask asyncTask) {
asyncTask.executeOnExecutor(executor);
}
private static class Tile {
private Rect sRect;
private int sampleSize;
private Bitmap bitmap;
private boolean loading;
private boolean visible;
// Volatile fields instantiated once then updated before use to reduce GC.
private Rect vRect;
private Rect fileSRect;
}
private static class Anim {
private float scaleStart; // Scale at start of anim
private float scaleEnd; // Scale at end of anim (target)
private PointF sCenterStart; // Source center point at start
private PointF sCenterEnd; // Source center point at end, adjusted for pan limits
private PointF sCenterEndRequested; // Source center point that was requested, without adjustment
private PointF vFocusStart; // View point that was double tapped
private PointF vFocusEnd; // Where the view focal point should be moved to during the anim
private long duration = 500; // How long the anim takes
private boolean interruptible = true; // Whether the anim can be interrupted by a touch
private int easing = EASE_IN_OUT_QUAD; // Easing style
private int origin = ORIGIN_ANIM; // Animation origin (API, double tap or fling)
private long time = System.currentTimeMillis(); // Start time
private OnAnimationEventListener listener; // Event listener
}
private static class ScaleAndTranslate {
private ScaleAndTranslate(float scale, PointF vTranslate) {
this.scale = scale;
this.vTranslate = vTranslate;
}
private float scale;
private final PointF vTranslate;
}
/**
* Set scale, center and orientation from saved state.
*/
private void restoreState(ImageViewState state) {
if (state != null && VALID_ORIENTATIONS.contains(state.getOrientation())) {
this.orientation = state.getOrientation();
this.pendingScale = state.getScale();
this.sPendingCenter = state.getCenter();
invalidate();
}
}
/**
* By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing {@link #TILE_SIZE_AUTO} will re-enable the default behaviour.
*
* @param maxPixels Maximum tile size X and Y in pixels.
*/
public void setMaxTileSize(int maxPixels) {
this.maxTileWidth = maxPixels;
this.maxTileHeight = maxPixels;
}
/**
* By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing {@link #TILE_SIZE_AUTO} will re-enable the default behaviour.
*
* @param maxPixelsX Maximum tile width.
* @param maxPixelsY Maximum tile height.
*/
public void setMaxTileSize(int maxPixelsX, int maxPixelsY) {
this.maxTileWidth = maxPixelsX;
this.maxTileHeight = maxPixelsY;
}
/**
* Use canvas max bitmap width and height instead of the default 2048, to avoid redundant tiling.
*/
@NonNull
private Point getMaxBitmapDimensions(Canvas canvas) {
return new Point(Math.min(canvas.getMaximumBitmapWidth(), maxTileWidth), Math.min(canvas.getMaximumBitmapHeight(), maxTileHeight));
}
/**
* Get source width taking rotation into account.
*/
@SuppressWarnings("SuspiciousNameCombination")
private int sWidth() {
int rotation = getRequiredRotation();
if (rotation == 90 || rotation == 270) {
return sHeight;
} else {
return sWidth;
}
}
/**
* Get source height taking rotation into account.
*/
@SuppressWarnings("SuspiciousNameCombination")
private int sHeight() {
int rotation = getRequiredRotation();
if (rotation == 90 || rotation == 270) {
return sWidth;
} else {
return sHeight;
}
}
/**
* Converts source rectangle from tile, which treats the image file as if it were in the correct orientation already,
* to the rectangle of the image that needs to be loaded.
*/
@SuppressWarnings("SuspiciousNameCombination")
@AnyThread
private void fileSRect(Rect sRect, Rect target) {
if (getRequiredRotation() == 0) {
target.set(sRect);
} else if (getRequiredRotation() == 90) {
target.set(sRect.top, sHeight - sRect.right, sRect.bottom, sHeight - sRect.left);
} else if (getRequiredRotation() == 180) {
target.set(sWidth - sRect.right, sHeight - sRect.bottom, sWidth - sRect.left, sHeight - sRect.top);
} else {
target.set(sWidth - sRect.bottom, sRect.left, sWidth - sRect.top, sRect.right);
}
}
/**
* Determines the rotation to be applied to tiles, based on EXIF orientation or chosen setting.
*/
@AnyThread
private int getRequiredRotation() {
if (orientation == ORIENTATION_USE_EXIF) {
return sOrientation;
} else {
return orientation;
}
}
/**
* Pythagoras distance between two points.
*/
private float distance(float x0, float x1, float y0, float y1) {
float x = x0 - x1;
float y = y0 - y1;
return (float) Math.sqrt(x * x + y * y);
}
/**
* Releases all resources the view is using and resets the state, nulling any fields that use significant memory.
* After you have called this method, the view can be re-used by setting a new image. Settings are remembered
* but state (scale and center) is forgotten. You can restore these yourself if required.
*/
public void recycle() {
reset(true);
bitmapPaint = null;
debugTextPaint = null;
debugLinePaint = null;
tileBgPaint = null;
}
/**
* Convert screen to source x coordinate.
*/
private float viewToSourceX(float vx) {
if (vTranslate == null) { return Float.NaN; }
return (vx - vTranslate.x)/scale;
}
/**
* Convert screen to source y coordinate.
*/
private float viewToSourceY(float vy) {
if (vTranslate == null) { return Float.NaN; }
return (vy - vTranslate.y)/scale;
}
/**
* Converts a rectangle within the view to the corresponding rectangle from the source file, taking
* into account the current scale, translation, orientation and clipped region. This can be used
* to decode a bitmap from the source file.
*
* This method will only work when the image has fully initialised, after {@link #isReady()} returns
* true. It is not guaranteed to work with preloaded bitmaps.
*
* The result is written to the fRect argument. Re-use a single instance for efficiency.
* @param vRect rectangle representing the view area to interpret.
* @param fRect rectangle instance to which the result will be written. Re-use for efficiency.
*/
public void viewToFileRect(Rect vRect, Rect fRect) {
if (vTranslate == null || !readySent) {
return;
}
fRect.set(
(int)viewToSourceX(vRect.left),
(int)viewToSourceY(vRect.top),
(int)viewToSourceX(vRect.right),
(int)viewToSourceY(vRect.bottom));
fileSRect(fRect, fRect);
fRect.set(
Math.max(0, fRect.left),
Math.max(0, fRect.top),
Math.min(sWidth, fRect.right),
Math.min(sHeight, fRect.bottom)
);
if (sRegion != null) {
fRect.offset(sRegion.left, sRegion.top);
}
}
/**
* Find the area of the source file that is currently visible on screen, taking into account the
* current scale, translation, orientation and clipped region. This is a convenience method; see
* {@link #viewToFileRect(Rect, Rect)}.
* @param fRect rectangle instance to which the result will be written. Re-use for efficiency.
*/
public void visibleFileRect(Rect fRect) {
if (vTranslate == null || !readySent) {
return;
}
fRect.set(0, 0, getWidth(), getHeight());
viewToFileRect(fRect, fRect);
}
/**
* Convert screen coordinate to source coordinate.
* @param vxy view X/Y coordinate.
* @return a coordinate representing the corresponding source coordinate.
*/
@Nullable
public final PointF viewToSourceCoord(PointF vxy) {
return viewToSourceCoord(vxy.x, vxy.y, new PointF());
}
/**
* Convert screen coordinate to source coordinate.
* @param vx view X coordinate.
* @param vy view Y coordinate.
* @return a coordinate representing the corresponding source coordinate.
*/
@Nullable
public final PointF viewToSourceCoord(float vx, float vy) {
return viewToSourceCoord(vx, vy, new PointF());
}
/**
* Convert screen coordinate to source coordinate.
* @param vxy view coordinates to convert.
* @param sTarget target object for result. The same instance is also returned.
* @return source coordinates. This is the same instance passed to the sTarget param.
*/
@Nullable
public final PointF viewToSourceCoord(PointF vxy, @NonNull PointF sTarget) {
return viewToSourceCoord(vxy.x, vxy.y, sTarget);
}
/**
* Convert screen coordinate to source coordinate.
* @param vx view X coordinate.
* @param vy view Y coordinate.
* @param sTarget target object for result. The same instance is also returned.
* @return source coordinates. This is the same instance passed to the sTarget param.
*/
@Nullable
public final PointF viewToSourceCoord(float vx, float vy, @NonNull PointF sTarget) {
if (vTranslate == null) {
return null;
}
sTarget.set(viewToSourceX(vx), viewToSourceY(vy));
return sTarget;
}
/**
* Convert source to view x coordinate.
*/
private float sourceToViewX(float sx) {
if (vTranslate == null) { return Float.NaN; }
return (sx * scale) + vTranslate.x;
}
/**
* Convert source to view y coordinate.
*/
private float sourceToViewY(float sy) {
if (vTranslate == null) { return Float.NaN; }
return (sy * scale) + vTranslate.y;
}
/**
* Convert source coordinate to view coordinate.
* @param sxy source coordinates to convert.
* @return view coordinates.
*/
@Nullable
public final PointF sourceToViewCoord(PointF sxy) {
return sourceToViewCoord(sxy.x, sxy.y, new PointF());
}
/**
* Convert source coordinate to view coordinate.
* @param sx source X coordinate.
* @param sy source Y coordinate.
* @return view coordinates.
*/
@Nullable
public final PointF sourceToViewCoord(float sx, float sy) {
return sourceToViewCoord(sx, sy, new PointF());
}
/**
* Convert source coordinate to view coordinate.
* @param sxy source coordinates to convert.
* @param vTarget target object for result. The same instance is also returned.
* @return view coordinates. This is the same instance passed to the vTarget param.
*/
@SuppressWarnings("UnusedReturnValue")
@Nullable
public final PointF sourceToViewCoord(PointF sxy, @NonNull PointF vTarget) {
return sourceToViewCoord(sxy.x, sxy.y, vTarget);
}
/**
* Convert source coordinate to view coordinate.
* @param sx source X coordinate.
* @param sy source Y coordinate.
* @param vTarget target object for result. The same instance is also returned.
* @return view coordinates. This is the same instance passed to the vTarget param.
*/
@Nullable
public final PointF sourceToViewCoord(float sx, float sy, @NonNull PointF vTarget) {
if (vTranslate == null) {
return null;
}
vTarget.set(sourceToViewX(sx), sourceToViewY(sy));
return vTarget;
}
/**
* Convert source rect to screen rect, integer values.
*/
private void sourceToViewRect(@NonNull Rect sRect, @NonNull Rect vTarget) {
vTarget.set(
(int)sourceToViewX(sRect.left),
(int)sourceToViewY(sRect.top),
(int)sourceToViewX(sRect.right),
(int)sourceToViewY(sRect.bottom)
);
}
/**
* Get the translation required to place a given source coordinate at the center of the screen, with the center
* adjusted for asymmetric padding. Accepts the desired scale as an argument, so this is independent of current
* translate and scale. The result is fitted to bounds, putting the image point as near to the screen center as permitted.
*/
@NonNull
private PointF vTranslateForSCenter(float sCenterX, float sCenterY, float scale) {
int vxCenter = getPaddingLeft() + (getWidth() - getPaddingRight() - getPaddingLeft())/2;
int vyCenter = getPaddingTop() + (getHeight() - getPaddingBottom() - getPaddingTop())/2;
if (satTemp == null) {
satTemp = new ScaleAndTranslate(0, new PointF(0, 0));
}
satTemp.scale = scale;
satTemp.vTranslate.set(vxCenter - (sCenterX * scale), vyCenter - (sCenterY * scale));
fitToBounds(true, satTemp);
return satTemp.vTranslate;
}
/**
* Given a requested source center and scale, calculate what the actual center will have to be to keep the image in
* pan limits, keeping the requested center as near to the middle of the screen as allowed.
*/
@NonNull
private PointF limitedSCenter(float sCenterX, float sCenterY, float scale, @NonNull PointF sTarget) {
PointF vTranslate = vTranslateForSCenter(sCenterX, sCenterY, scale);
int vxCenter = getPaddingLeft() + (getWidth() - getPaddingRight() - getPaddingLeft())/2;
int vyCenter = getPaddingTop() + (getHeight() - getPaddingBottom() - getPaddingTop())/2;
float sx = (vxCenter - vTranslate.x)/scale;
float sy = (vyCenter - vTranslate.y)/scale;
sTarget.set(sx, sy);
return sTarget;
}
/**
* Returns the minimum allowed scale.
*/
private float minScale() {
int vPadding = getPaddingBottom() + getPaddingTop();
int hPadding = getPaddingLeft() + getPaddingRight();
if (minimumScaleType == SCALE_TYPE_CENTER_CROP || minimumScaleType == SCALE_TYPE_START) {
return Math.max((getWidth() - hPadding) / (float) sWidth(), (getHeight() - vPadding) / (float) sHeight());
} else if (minimumScaleType == SCALE_TYPE_CUSTOM && minScale > 0) {
return minScale;
} else {
return Math.min((getWidth() - hPadding) / (float) sWidth(), (getHeight() - vPadding) / (float) sHeight());
}
}
/**
* Adjust a requested scale to be within the allowed limits.
*/
private float limitedScale(float targetScale) {
targetScale = Math.max(minScale(), targetScale);
targetScale = Math.min(maxScale, targetScale);
return targetScale;
}
/**
* Apply a selected type of easing.
* @param type Easing type, from static fields
* @param time Elapsed time
* @param from Start value
* @param change Target value
* @param duration Anm duration
* @return Current value
*/
private float ease(int type, long time, float from, float change, long duration) {
switch (type) {
case EASE_IN_OUT_QUAD:
return easeInOutQuad(time, from, change, duration);
case EASE_OUT_QUAD:
return easeOutQuad(time, from, change, duration);
default:
throw new IllegalStateException("Unexpected easing type: " + type);
}
}
/**
* Quadratic easing for fling. With thanks to Robert Penner - http://gizma.com/easing/
* @param time Elapsed time
* @param from Start value
* @param change Target value
* @param duration Anm duration
* @return Current value
*/
private float easeOutQuad(long time, float from, float change, long duration) {
float progress = (float)time/(float)duration;
return -change * progress*(progress-2) + from;
}
/**
* Quadratic easing for scale and center animations. With thanks to Robert Penner - http://gizma.com/easing/
* @param time Elapsed time
* @param from Start value
* @param change Target value
* @param duration Anm duration
* @return Current value
*/
private float easeInOutQuad(long time, float from, float change, long duration) {
float timeF = time/(duration/2f);
if (timeF < 1) {
return (change/2f * timeF * timeF) + from;
} else {
timeF--;
return (-change/2f) * (timeF * (timeF - 2) - 1) + from;
}
}
/**
* Debug logger
*/
@AnyThread
private void debug(String message, Object... args) {
if (debug) {
Log.d(TAG, String.format(message, args));
}
}
/**
* For debug overlays. Scale pixel value according to screen density.
*/
private int px(int px) {
return (int)(density * px);
}
/**
*
* Swap the default region decoder implementation for one of your own. You must do this before setting the image file or
* asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a
* public default constructor.
* @param regionDecoderClass The {@link ImageRegionDecoder} implementation to use.
*/
public final void setRegionDecoderClass(@NonNull Class extends ImageRegionDecoder> regionDecoderClass) {
//noinspection ConstantConditions
if (regionDecoderClass == null) {
throw new IllegalArgumentException("Decoder class cannot be set to null");
}
this.regionDecoderFactory = new CompatDecoderFactory<>(regionDecoderClass);
}
/**
* Swap the default region decoder implementation for one of your own. You must do this before setting the image file or
* asset, and you cannot use a custom decoder when using layout XML to set an asset name.
* @param regionDecoderFactory The {@link DecoderFactory} implementation that produces {@link ImageRegionDecoder}
* instances.
*/
public final void setRegionDecoderFactory(@NonNull DecoderFactory extends ImageRegionDecoder> regionDecoderFactory) {
//noinspection ConstantConditions
if (regionDecoderFactory == null) {
throw new IllegalArgumentException("Decoder factory cannot be set to null");
}
this.regionDecoderFactory = regionDecoderFactory;
}
/**
* Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or
* asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a
* public default constructor.
* @param bitmapDecoderClass The {@link ImageDecoder} implementation to use.
*/
public final void setBitmapDecoderClass(@NonNull Class extends ImageDecoder> bitmapDecoderClass) {
//noinspection ConstantConditions
if (bitmapDecoderClass == null) {
throw new IllegalArgumentException("Decoder class cannot be set to null");
}
this.bitmapDecoderFactory = new CompatDecoderFactory<>(bitmapDecoderClass);
}
/**
* Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or
* asset, and you cannot use a custom decoder when using layout XML to set an asset name.
* @param bitmapDecoderFactory The {@link DecoderFactory} implementation that produces {@link ImageDecoder} instances.
*/
public final void setBitmapDecoderFactory(@NonNull DecoderFactory extends ImageDecoder> bitmapDecoderFactory) {
//noinspection ConstantConditions
if (bitmapDecoderFactory == null) {
throw new IllegalArgumentException("Decoder factory cannot be set to null");
}
this.bitmapDecoderFactory = bitmapDecoderFactory;
}
/**
* Calculate how much further the image can be panned in each direction. The results are set on
* the supplied {@link RectF} and expressed as screen pixels. For example, if the image cannot be
* panned any further towards the left, the value of {@link RectF#left} will be set to 0.
* @param vTarget target object for results. Re-use for efficiency.
*/
public final void getPanRemaining(RectF vTarget) {
if (!isReady()) {
return;
}
float scaleWidth = scale * sWidth();
float scaleHeight = scale * sHeight();
if (panLimit == PAN_LIMIT_CENTER) {
vTarget.top = Math.max(0, -(vTranslate.y - (getHeight() / 2)));
vTarget.left = Math.max(0, -(vTranslate.x - (getWidth() / 2)));
vTarget.bottom = Math.max(0, vTranslate.y - ((getHeight() / 2) - scaleHeight));
vTarget.right = Math.max(0, vTranslate.x - ((getWidth() / 2) - scaleWidth));
} else if (panLimit == PAN_LIMIT_OUTSIDE) {
vTarget.top = Math.max(0, -(vTranslate.y - getHeight()));
vTarget.left = Math.max(0, -(vTranslate.x - getWidth()));
vTarget.bottom = Math.max(0, vTranslate.y + scaleHeight);
vTarget.right = Math.max(0, vTranslate.x + scaleWidth);
} else {
vTarget.top = Math.max(0, -vTranslate.y);
vTarget.left = Math.max(0, -vTranslate.x);
vTarget.bottom = Math.max(0, (scaleHeight + vTranslate.y) - getHeight());
vTarget.right = Math.max(0, (scaleWidth + vTranslate.x) - getWidth());
}
}
/**
* Set the pan limiting style. See static fields. Normally {@link #PAN_LIMIT_INSIDE} is best, for image galleries.
* @param panLimit a pan limit constant. See static fields.
*/
public final void setPanLimit(int panLimit) {
if (!VALID_PAN_LIMITS.contains(panLimit)) {
throw new IllegalArgumentException("Invalid pan limit: " + panLimit);
}
this.panLimit = panLimit;
if (isReady()) {
fitToBounds(true);
invalidate();
}
}
/**
* Set the minimum scale type. See static fields. Normally {@link #SCALE_TYPE_CENTER_INSIDE} is best, for image galleries.
* @param scaleType a scale type constant. See static fields.
*/
public final void setMinimumScaleType(int scaleType) {
if (!VALID_SCALE_TYPES.contains(scaleType)) {
throw new IllegalArgumentException("Invalid scale type: " + scaleType);
}
this.minimumScaleType = scaleType;
if (isReady()) {
fitToBounds(true);
invalidate();
}
}
/**
* Set the maximum scale allowed. A value of 1 means 1:1 pixels at maximum scale. You may wish to set this according
* to screen density - on a retina screen, 1:1 may still be too small. Consider using {@link #setMinimumDpi(int)},
* which is density aware.
* @param maxScale maximum scale expressed as a source/view pixels ratio.
*/
public final void setMaxScale(float maxScale) {
this.maxScale = maxScale;
}
/**
* Set the minimum scale allowed. A value of 1 means 1:1 pixels at minimum scale. You may wish to set this according
* to screen density. Consider using {@link #setMaximumDpi(int)}, which is density aware.
* @param minScale minimum scale expressed as a source/view pixels ratio.
*/
public final void setMinScale(float minScale) {
this.minScale = minScale;
}
/**
* This is a screen density aware alternative to {@link #setMaxScale(float)}; it allows you to express the maximum
* allowed scale in terms of the minimum pixel density. This avoids the problem of 1:1 scale still being
* too small on a high density screen. A sensible starting point is 160 - the default used by this view.
* @param dpi Source image pixel density at maximum zoom.
*/
public final void setMinimumDpi(int dpi) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float averageDpi = (metrics.xdpi + metrics.ydpi)/2;
setMaxScale(averageDpi/dpi);
}
/**
* This is a screen density aware alternative to {@link #setMinScale(float)}; it allows you to express the minimum
* allowed scale in terms of the maximum pixel density.
* @param dpi Source image pixel density at minimum zoom.
*/
public final void setMaximumDpi(int dpi) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float averageDpi = (metrics.xdpi + metrics.ydpi)/2;
setMinScale(averageDpi / dpi);
}
/**
* Returns the maximum allowed scale.
* @return the maximum scale as a source/view pixels ratio.
*/
public float getMaxScale() {
return maxScale;
}
/**
* Returns the minimum allowed scale.
* @return the minimum scale as a source/view pixels ratio.
*/
public final float getMinScale() {
return minScale();
}
/**
* By default, image tiles are at least as high resolution as the screen. For a retina screen this may not be
* necessary, and may increase the likelihood of an OutOfMemoryError. This method sets a DPI at which higher
* resolution tiles should be loaded. Using a lower number will on average use less memory but result in a lower
* quality image. 160-240dpi will usually be enough. This should be called before setting the image source,
* because it affects which tiles get loaded. When using an untiled source image this method has no effect.
* @param minimumTileDpi Tile loading threshold.
*/
public void setMinimumTileDpi(int minimumTileDpi) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float averageDpi = (metrics.xdpi + metrics.ydpi)/2;
this.minimumTileDpi = (int)Math.min(averageDpi, minimumTileDpi);
if (isReady()) {
reset(false);
invalidate();
}
}
/**
* Returns the source point at the center of the view.
* @return the source coordinates current at the center of the view.
*/
@Nullable
public final PointF getCenter() {
int mX = getWidth()/2;
int mY = getHeight()/2;
return viewToSourceCoord(mX, mY);
}
/**
* Returns the current scale value.
* @return the current scale as a source/view pixels ratio.
*/
public final float getScale() {
return scale;
}
/**
* Externally change the scale and translation of the source image. This may be used with getCenter() and getScale()
* to restore the scale and zoom after a screen rotate.
* @param scale New scale to set.
* @param sCenter New source image coordinate to center on the screen, subject to boundaries.
*/
public final void setScaleAndCenter(float scale, @Nullable PointF sCenter) {
this.anim = null;
this.pendingScale = scale;
this.sPendingCenter = sCenter;
this.sRequestedCenter = sCenter;
invalidate();
}
/**
* Fully zoom out and return the image to the middle of the screen. This might be useful if you have a view pager
* and want images to be reset when the user has moved to another page.
*/
public final void resetScaleAndCenter() {
this.anim = null;
this.pendingScale = limitedScale(0);
if (isReady()) {
this.sPendingCenter = new PointF(sWidth()/2, sHeight()/2);
} else {
this.sPendingCenter = new PointF(0, 0);
}
invalidate();
}
/**
* Call to find whether the view is initialised, has dimensions, and will display an image on
* the next draw. If a preview has been provided, it may be the preview that will be displayed
* and the full size image may still be loading. If no preview was provided, this is called once
* the base layer tiles of the full size image are loaded.
* @return true if the view is ready to display an image and accept touch gestures.
*/
public final boolean isReady() {
return readySent;
}
/**
* Called once when the view is initialised, has dimensions, and will display an image on the
* next draw. This is triggered at the same time as {@link OnImageEventListener#onReady()} but
* allows a subclass to receive this event without using a listener.
*/
@SuppressWarnings("EmptyMethod")
protected void onReady() {
}
/**
* Call to find whether the main image (base layer tiles where relevant) have been loaded. Before
* this event the view is blank unless a preview was provided.
* @return true if the main image (not the preview) has been loaded and is ready to display.
*/
public final boolean isImageLoaded() {
return imageLoadedSent;
}
/**
* Called once when the full size image or its base layer tiles have been loaded.
*/
@SuppressWarnings("EmptyMethod")
protected void onImageLoaded() {
}
/**
* Get source width, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSHeight()}
* for the apparent width.
* @return the source image width in pixels.
*/
public final int getSWidth() {
return sWidth;
}
/**
* Get source height, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSWidth()}
* for the apparent height.
* @return the source image height in pixels.
*/
public final int getSHeight() {
return sHeight;
}
/**
* Returns the orientation setting. This can return {@link #ORIENTATION_USE_EXIF}, in which case it doesn't tell you
* the applied orientation of the image. For that, use {@link #getAppliedOrientation()}.
* @return the orientation setting. See static fields.
*/
public final int getOrientation() {
return orientation;
}
/**
* Returns the actual orientation of the image relative to the source file. This will be based on the source file's
* EXIF orientation if you're using ORIENTATION_USE_EXIF. Values are 0, 90, 180, 270.
* @return the orientation applied after EXIF information has been extracted. See static fields.
*/
public final int getAppliedOrientation() {
return getRequiredRotation();
}
/**
* Get the current state of the view (scale, center, orientation) for restoration after rotate. Will return null if
* the view is not ready.
* @return an {@link ImageViewState} instance representing the current position of the image. null if the view isn't ready.
*/
@Nullable
public final ImageViewState getState() {
if (vTranslate != null && sWidth > 0 && sHeight > 0) {
//noinspection ConstantConditions
return new ImageViewState(getScale(), getCenter(), getOrientation());
}
return null;
}
/**
* Returns true if zoom gesture detection is enabled.
* @return true if zoom gesture detection is enabled.
*/
public final boolean isZoomEnabled() {
return zoomEnabled;
}
/**
* Enable or disable zoom gesture detection. Disabling zoom locks the the current scale.
* @param zoomEnabled true to enable zoom gestures, false to disable.
*/
public final void setZoomEnabled(boolean zoomEnabled) {
this.zoomEnabled = zoomEnabled;
}
/**
* Returns true if double tap & swipe to zoom is enabled.
* @return true if double tap & swipe to zoom is enabled.
*/
public final boolean isQuickScaleEnabled() {
return quickScaleEnabled;
}
/**
* Enable or disable double tap & swipe to zoom.
* @param quickScaleEnabled true to enable quick scale, false to disable.
*/
public final void setQuickScaleEnabled(boolean quickScaleEnabled) {
this.quickScaleEnabled = quickScaleEnabled;
}
/**
* Returns true if pan gesture detection is enabled.
* @return true if pan gesture detection is enabled.
*/
public final boolean isPanEnabled() {
return panEnabled;
}
/**
* Enable or disable pan gesture detection. Disabling pan causes the image to be centered. Pan
* can still be changed from code.
* @param panEnabled true to enable panning, false to disable.
*/
public final void setPanEnabled(boolean panEnabled) {
this.panEnabled = panEnabled;
if (!panEnabled && vTranslate != null) {
vTranslate.x = (getWidth()/2) - (scale * (sWidth()/2));
vTranslate.y = (getHeight()/2) - (scale * (sHeight()/2));
if (isReady()) {
refreshRequiredTiles(true);
invalidate();
}
}
}
/**
* Set a solid color to render behind tiles, useful for displaying transparent PNGs.
* @param tileBgColor Background color for tiles.
*/
public final void setTileBackgroundColor(int tileBgColor) {
if (Color.alpha(tileBgColor) == 0) {
tileBgPaint = null;
} else {
tileBgPaint = new Paint();
tileBgPaint.setStyle(Style.FILL);
tileBgPaint.setColor(tileBgColor);
}
invalidate();
}
/**
* Set the scale the image will zoom in to when double tapped. This also the scale point where a double tap is interpreted
* as a zoom out gesture - if the scale is greater than 90% of this value, a double tap zooms out. Avoid using values
* greater than the max zoom.
* @param doubleTapZoomScale New value for double tap gesture zoom scale.
*/
public final void setDoubleTapZoomScale(float doubleTapZoomScale) {
this.doubleTapZoomScale = doubleTapZoomScale;
}
/**
* A density aware alternative to {@link #setDoubleTapZoomScale(float)}; this allows you to express the scale the
* image will zoom in to when double tapped in terms of the image pixel density. Values lower than the max scale will
* be ignored. A sensible starting point is 160 - the default used by this view.
* @param dpi New value for double tap gesture zoom scale.
*/
public final void setDoubleTapZoomDpi(int dpi) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float averageDpi = (metrics.xdpi + metrics.ydpi)/2;
setDoubleTapZoomScale(averageDpi/dpi);
}
/**
* Set the type of zoom animation to be used for double taps. See static fields.
* @param doubleTapZoomStyle New value for zoom style.
*/
public final void setDoubleTapZoomStyle(int doubleTapZoomStyle) {
if (!VALID_ZOOM_STYLES.contains(doubleTapZoomStyle)) {
throw new IllegalArgumentException("Invalid zoom style: " + doubleTapZoomStyle);
}
this.doubleTapZoomStyle = doubleTapZoomStyle;
}
/**
* Set the duration of the double tap zoom animation.
* @param durationMs Duration in milliseconds.
*/
public final void setDoubleTapZoomDuration(int durationMs) {
this.doubleTapZoomDuration = Math.max(0, durationMs);
}
/**
*
* Provide an {@link Executor} to be used for loading images. By default, {@link AsyncTask#THREAD_POOL_EXECUTOR}
* is used to minimise contention with other background work the app is doing. You can also choose
* to use {@link AsyncTask#SERIAL_EXECUTOR} if you want to limit concurrent background tasks.
* Alternatively you can supply an {@link Executor} of your own to avoid any contention. It is
* strongly recommended to use a single executor instance for the life of your application, not
* one per view instance.
*
* Warning: If you are using a custom implementation of {@link ImageRegionDecoder}, and you
* supply an executor with more than one thread, you must make sure your implementation supports
* multi-threaded bitmap decoding or has appropriate internal synchronization. From SDK 21, Android's
* {@link android.graphics.BitmapRegionDecoder} uses an internal lock so it is thread safe but
* there is no advantage to using multiple threads.
*
* @param executor an {@link Executor} for image loading.
*/
public void setExecutor(@NonNull Executor executor) {
//noinspection ConstantConditions
if (executor == null) {
throw new NullPointerException("Executor must not be null");
}
this.executor = executor;
}
/**
* Enable or disable eager loading of tiles that appear on screen during gestures or animations,
* while the gesture or animation is still in progress. By default this is enabled to improve
* responsiveness, but it can result in tiles being loaded and discarded more rapidly than
* necessary and reduce the animation frame rate on old/cheap devices. Disable this on older
* devices if you see poor performance. Tiles will then be loaded only when gestures and animations
* are completed.
* @param eagerLoadingEnabled true to enable loading during gestures, false to delay loading until gestures end
*/
public void setEagerLoadingEnabled(boolean eagerLoadingEnabled) {
this.eagerLoadingEnabled = eagerLoadingEnabled;
}
/**
* Enables visual debugging, showing tile boundaries and sizes.
* @param debug true to enable debugging, false to disable.
*/
public final void setDebug(boolean debug) {
this.debug = debug;
}
/**
* Check if an image has been set. The image may not have been loaded and displayed yet.
* @return If an image is currently set.
*/
public boolean hasImage() {
return uri != null || bitmap != null;
}
/**
* {@inheritDoc}
*/
@Override
public void setOnLongClickListener(OnLongClickListener onLongClickListener) {
this.onLongClickListener = onLongClickListener;
}
/**
* Add a listener allowing notification of load and error events. Extend {@link DefaultOnImageEventListener}
* to simplify implementation.
* @param onImageEventListener an {@link OnImageEventListener} instance.
*/
public void setOnImageEventListener(OnImageEventListener onImageEventListener) {
this.onImageEventListener = onImageEventListener;
}
/**
* Add a listener for pan and zoom events. Extend {@link DefaultOnStateChangedListener} to simplify
* implementation.
* @param onStateChangedListener an {@link OnStateChangedListener} instance.
*/
public void setOnStateChangedListener(OnStateChangedListener onStateChangedListener) {
this.onStateChangedListener = onStateChangedListener;
}
private void sendStateChanged(float oldScale, PointF oldVTranslate, int origin) {
if (onStateChangedListener != null && scale != oldScale) {
onStateChangedListener.onScaleChanged(scale, origin);
}
if (onStateChangedListener != null && !vTranslate.equals(oldVTranslate)) {
onStateChangedListener.onCenterChanged(getCenter(), origin);
}
}
/**
* Creates a panning animation builder, that when started will animate the image to place the given coordinates of
* the image in the center of the screen. If doing this would move the image beyond the edges of the screen, the
* image is instead animated to move the center point as near to the center of the screen as is allowed - it's
* guaranteed to be on screen.
* @param sCenter Target center point
* @return {@link AnimationBuilder} instance. Call {@link SubsamplingScaleImageView.AnimationBuilder#start()} to start the anim.
*/
@Nullable
public AnimationBuilder animateCenter(PointF sCenter) {
if (!isReady()) {
return null;
}
return new AnimationBuilder(sCenter);
}
/**
* Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image
* beyond the panning limits, the image is automatically panned during the animation.
* @param scale Target scale.
* @return {@link AnimationBuilder} instance. Call {@link SubsamplingScaleImageView.AnimationBuilder#start()} to start the anim.
*/
@Nullable
public AnimationBuilder animateScale(float scale) {
if (!isReady()) {
return null;
}
return new AnimationBuilder(scale);
}
/**
* Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image
* beyond the panning limits, the image is automatically panned during the animation.
* @param scale Target scale.
* @param sCenter Target source center.
* @return {@link AnimationBuilder} instance. Call {@link SubsamplingScaleImageView.AnimationBuilder#start()} to start the anim.
*/
@Nullable
public AnimationBuilder animateScaleAndCenter(float scale, PointF sCenter) {
if (!isReady()) {
return null;
}
return new AnimationBuilder(scale, sCenter);
}
/**
* Builder class used to set additional options for a scale animation. Create an instance using {@link #animateScale(float)},
* then set your options and call {@link #start()}.
*/
public final class AnimationBuilder {
private final float targetScale;
private final PointF targetSCenter;
private final PointF vFocus;
private long duration = 500;
private int easing = EASE_IN_OUT_QUAD;
private int origin = ORIGIN_ANIM;
private boolean interruptible = true;
private boolean panLimited = true;
private OnAnimationEventListener listener;
private AnimationBuilder(PointF sCenter) {
this.targetScale = scale;
this.targetSCenter = sCenter;
this.vFocus = null;
}
private AnimationBuilder(float scale) {
this.targetScale = scale;
this.targetSCenter = getCenter();
this.vFocus = null;
}
private AnimationBuilder(float scale, PointF sCenter) {
this.targetScale = scale;
this.targetSCenter = sCenter;
this.vFocus = null;
}
private AnimationBuilder(float scale, PointF sCenter, PointF vFocus) {
this.targetScale = scale;
this.targetSCenter = sCenter;
this.vFocus = vFocus;
}
/**
* Desired duration of the anim in milliseconds. Default is 500.
* @param duration duration in milliseconds.
* @return this builder for method chaining.
*/
@NonNull
public AnimationBuilder withDuration(long duration) {
this.duration = duration;
return this;
}
/**
* Whether the animation can be interrupted with a touch. Default is true.
* @param interruptible interruptible flag.
* @return this builder for method chaining.
*/
@NonNull
public AnimationBuilder withInterruptible(boolean interruptible) {
this.interruptible = interruptible;
return this;
}
/**
* Set the easing style. See static fields. {@link #EASE_IN_OUT_QUAD} is recommended, and the default.
* @param easing easing style.
* @return this builder for method chaining.
*/
@NonNull
public AnimationBuilder withEasing(int easing) {
if (!VALID_EASING_STYLES.contains(easing)) {
throw new IllegalArgumentException("Unknown easing type: " + easing);
}
this.easing = easing;
return this;
}
/**
* Add an animation event listener.
* @param listener The listener.
* @return this builder for method chaining.
*/
@NonNull
public AnimationBuilder withOnAnimationEventListener(OnAnimationEventListener listener) {
this.listener = listener;
return this;
}
/**
* Only for internal use. When set to true, the animation proceeds towards the actual end point - the nearest
* point to the center allowed by pan limits. When false, animation is in the direction of the requested end
* point and is stopped when the limit for each axis is reached. The latter behaviour is used for flings but
* nothing else.
*/
@NonNull
private AnimationBuilder withPanLimited(boolean panLimited) {
this.panLimited = panLimited;
return this;
}
/**
* Only for internal use. Indicates what caused the animation.
*/
@NonNull
private AnimationBuilder withOrigin(int origin) {
this.origin = origin;
return this;
}
/**
* Starts the animation.
*/
public void start() {
if (anim != null && anim.listener != null) {
try {
anim.listener.onInterruptedByNewAnim();
} catch (Exception e) {
Log.w(TAG, "Error thrown by animation listener", e);
}
}
int vxCenter = getPaddingLeft() + (getWidth() - getPaddingRight() - getPaddingLeft())/2;
int vyCenter = getPaddingTop() + (getHeight() - getPaddingBottom() - getPaddingTop())/2;
float targetScale = limitedScale(this.targetScale);
PointF targetSCenter = panLimited ? limitedSCenter(this.targetSCenter.x, this.targetSCenter.y, targetScale, new PointF()) : this.targetSCenter;
anim = new Anim();
anim.scaleStart = scale;
anim.scaleEnd = targetScale;
anim.time = System.currentTimeMillis();
anim.sCenterEndRequested = targetSCenter;
anim.sCenterStart = getCenter();
anim.sCenterEnd = targetSCenter;
anim.vFocusStart = sourceToViewCoord(targetSCenter);
anim.vFocusEnd = new PointF(
vxCenter,
vyCenter
);
anim.duration = duration;
anim.interruptible = interruptible;
anim.easing = easing;
anim.origin = origin;
anim.time = System.currentTimeMillis();
anim.listener = listener;
if (vFocus != null) {
// Calculate where translation will be at the end of the anim
float vTranslateXEnd = vFocus.x - (targetScale * anim.sCenterStart.x);
float vTranslateYEnd = vFocus.y - (targetScale * anim.sCenterStart.y);
ScaleAndTranslate satEnd = new ScaleAndTranslate(targetScale, new PointF(vTranslateXEnd, vTranslateYEnd));
// Fit the end translation into bounds
fitToBounds(true, satEnd);
// Adjust the position of the focus point at end so image will be in bounds
anim.vFocusEnd = new PointF(
vFocus.x + (satEnd.vTranslate.x - vTranslateXEnd),
vFocus.y + (satEnd.vTranslate.y - vTranslateYEnd)
);
}
invalidate();
}
}
/**
* An event listener for animations, allows events to be triggered when an animation completes,
* is aborted by another animation starting, or is aborted by a touch event. Note that none of
* these events are triggered if the activity is paused, the image is swapped, or in other cases
* where the view's internal state gets wiped or draw events stop.
*/
@SuppressWarnings("EmptyMethod")
public interface OnAnimationEventListener {
/**
* The animation has completed, having reached its endpoint.
*/
void onComplete();
/**
* The animation has been aborted before reaching its endpoint because the user touched the screen.
*/
void onInterruptedByUser();
/**
* The animation has been aborted before reaching its endpoint because a new animation has been started.
*/
void onInterruptedByNewAnim();
}
/**
* Default implementation of {@link OnAnimationEventListener} for extension. This does nothing in any method.
*/
public static class DefaultOnAnimationEventListener implements OnAnimationEventListener {
@Override public void onComplete() { }
@Override public void onInterruptedByUser() { }
@Override public void onInterruptedByNewAnim() { }
}
/**
* An event listener, allowing subclasses and activities to be notified of significant events.
*/
@SuppressWarnings("EmptyMethod")
public interface OnImageEventListener {
/**
* Called when the dimensions of the image and view are known, and either a preview image,
* the full size image, or base layer tiles are loaded. This indicates the scale and translate
* are known and the next draw will display an image. This event can be used to hide a loading
* graphic, or inform a subclass that it is safe to draw overlays.
*/
void onReady();
/**
* Called when the full size image is ready. When using tiling, this means the lowest resolution
* base layer of tiles are loaded, and when tiling is disabled, the image bitmap is loaded.
* This event could be used as a trigger to enable gestures if you wanted interaction disabled
* while only a preview is displayed, otherwise for most cases {@link #onReady()} is the best
* event to listen to.
*/
void onImageLoaded();
/**
* Called when a preview image could not be loaded. This method cannot be relied upon; certain
* encoding types of supported image formats can result in corrupt or blank images being loaded
* and displayed with no detectable error. The view will continue to load the full size image.
* @param e The exception thrown. This error is logged by the view.
*/
void onPreviewLoadError(Exception e);
/**
* Indicates an error initiliasing the decoder when using a tiling, or when loading the full
* size bitmap when tiling is disabled. This method cannot be relied upon; certain encoding
* types of supported image formats can result in corrupt or blank images being loaded and
* displayed with no detectable error.
* @param e The exception thrown. This error is also logged by the view.
*/
void onImageLoadError(Exception e);
/**
* Called when an image tile could not be loaded. This method cannot be relied upon; certain
* encoding types of supported image formats can result in corrupt or blank images being loaded
* and displayed with no detectable error. Most cases where an unsupported file is used will
* result in an error caught by {@link #onImageLoadError(Exception)}.
* @param e The exception thrown. This error is logged by the view.
*/
void onTileLoadError(Exception e);
/**
* Called when a bitmap set using ImageSource.cachedBitmap is no longer being used by the View.
* This is useful if you wish to manage the bitmap after the preview is shown
*/
void onPreviewReleased();
}
/**
* Default implementation of {@link OnImageEventListener} for extension. This does nothing in any method.
*/
public static class DefaultOnImageEventListener implements OnImageEventListener {
@Override public void onReady() { }
@Override public void onImageLoaded() { }
@Override public void onPreviewLoadError(Exception e) { }
@Override public void onImageLoadError(Exception e) { }
@Override public void onTileLoadError(Exception e) { }
@Override public void onPreviewReleased() { }
}
/**
* An event listener, allowing activities to be notified of pan and zoom events. Initialisation
* and calls made by your code do not trigger events; touch events and animations do. Methods in
* this listener will be called on the UI thread and may be called very frequently - your
* implementation should return quickly.
*/
@SuppressWarnings("EmptyMethod")
public interface OnStateChangedListener {
/**
* The scale has changed. Use with {@link #getMaxScale()} and {@link #getMinScale()} to determine
* whether the image is fully zoomed in or out.
* @param newScale The new scale.
* @param origin Where the event originated from - one of {@link #ORIGIN_ANIM}, {@link #ORIGIN_TOUCH}.
*/
void onScaleChanged(float newScale, int origin);
/**
* The source center has been changed. This can be a result of panning or zooming.
* @param newCenter The new source center point.
* @param origin Where the event originated from - one of {@link #ORIGIN_ANIM}, {@link #ORIGIN_TOUCH}.
*/
void onCenterChanged(PointF newCenter, int origin);
}
/**
* Default implementation of {@link OnStateChangedListener}. This does nothing in any method.
*/
public static class DefaultOnStateChangedListener implements OnStateChangedListener {
@Override public void onCenterChanged(PointF newCenter, int origin) { }
@Override public void onScaleChanged(float newScale, int origin) { }
}
}
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/decoder/CompatDecoderFactory.java
================================================
package com.davemorrissey.labs.subscaleview.decoder;
import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Compatibility factory to instantiate decoders with empty public constructors.
* @param The base type of the decoder this factory will produce.
*/
@SuppressWarnings("WeakerAccess")
public class CompatDecoderFactory implements DecoderFactory {
private final Class extends T> clazz;
private final Bitmap.Config bitmapConfig;
/**
* Construct a factory for the given class. This must have a default constructor.
* @param clazz a class that implements {@link ImageDecoder} or {@link ImageRegionDecoder}.
*/
public CompatDecoderFactory(@NonNull Class extends T> clazz) {
this(clazz, null);
}
/**
* Construct a factory for the given class. This must have a constructor that accepts a {@link Bitmap.Config} instance.
* @param clazz a class that implements {@link ImageDecoder} or {@link ImageRegionDecoder}.
* @param bitmapConfig bitmap configuration to be used when loading images.
*/
public CompatDecoderFactory(@NonNull Class extends T> clazz, Bitmap.Config bitmapConfig) {
this.clazz = clazz;
this.bitmapConfig = bitmapConfig;
}
@Override
@NonNull
public T make() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
if (bitmapConfig == null) {
return clazz.newInstance();
} else {
Constructor extends T> ctor = clazz.getConstructor(Bitmap.Config.class);
return ctor.newInstance(bitmapConfig);
}
}
}
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/decoder/DecoderFactory.java
================================================
package com.davemorrissey.labs.subscaleview.decoder;
import androidx.annotation.NonNull;
import java.lang.reflect.InvocationTargetException;
/**
* Interface for {@link ImageDecoder} and {@link ImageRegionDecoder} factories.
* @param the class of decoder that will be produced.
*/
public interface DecoderFactory {
/**
* Produce a new instance of a decoder with type {@link T}.
* @return a new instance of your decoder.
* @throws IllegalAccessException if the factory class cannot be instantiated.
* @throws InstantiationException if the factory class cannot be instantiated.
* @throws NoSuchMethodException if the factory class cannot be instantiated.
* @throws InvocationTargetException if the factory class cannot be instantiated.
*/
@NonNull T make() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException;
}
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/decoder/ImageDecoder.java
================================================
package com.davemorrissey.labs.subscaleview.decoder;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import androidx.annotation.NonNull;
/**
* Interface for image decoding classes, allowing the default {@link android.graphics.BitmapFactory}
* based on the Skia library to be replaced with a custom class.
*/
public interface ImageDecoder {
/**
* Decode an image. The URI can be in one of the following formats:
*
* File: file:///scard/picture.jpg
*
* Asset: file:///android_asset/picture.png
*
* Resource: android.resource://com.example.app/drawable/picture
*
* @param context Application context
* @param uri URI of the image
* @return the decoded bitmap
* @throws Exception if decoding fails.
*/
@NonNull Bitmap decode(Context context, @NonNull Uri uri) throws Exception;
}
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/decoder/ImageRegionDecoder.java
================================================
package com.davemorrissey.labs.subscaleview.decoder;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import androidx.annotation.NonNull;
/**
* Interface for image decoding classes, allowing the default {@link android.graphics.BitmapRegionDecoder}
* based on the Skia library to be replaced with a custom class.
*/
public interface ImageRegionDecoder {
/**
* Initialise the decoder. When possible, perform initial setup work once in this method. The
* dimensions of the image must be returned. The URI can be in one of the following formats:
*
* File: file:///scard/picture.jpg
*
* Asset: file:///android_asset/picture.png
*
* Resource: android.resource://com.example.app/drawable/picture
* @param context Application context. A reference may be held, but must be cleared on recycle.
* @param uri URI of the image.
* @return Dimensions of the image.
* @throws Exception if initialisation fails.
*/
@NonNull Point init(Context context, @NonNull Uri uri) throws Exception;
/**
*
* Decode a region of the image with the given sample size. This method is called off the UI
* thread so it can safely load the image on the current thread. It is called from
* {@link android.os.AsyncTask}s running in an executor that may have multiple threads, so
* implementations must be thread safe. Adding synchronized to the method signature
* is the simplest way to achieve this, but bear in mind the {@link #recycle()} method can be
* called concurrently.
*
* See {@link SkiaImageRegionDecoder} and {@link SkiaPooledImageRegionDecoder} for examples of
* internal locking and synchronization.
*
* @param sRect Source image rectangle to decode.
* @param sampleSize Sample size.
* @return The decoded region. It is safe to return null if decoding fails.
*/
@NonNull Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize);
/**
* Status check. Should return false before initialisation and after recycle.
* @return true if the decoder is ready to be used.
*/
boolean isReady();
/**
* This method will be called when the decoder is no longer required. It should clean up any resources still in use.
*/
void recycle();
}
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/decoder/SkiaImageDecoder.java
================================================
package com.davemorrissey.labs.subscaleview.decoder;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import java.io.InputStream;
import java.util.List;
/**
* Default implementation of {@link com.davemorrissey.labs.subscaleview.decoder.ImageDecoder}
* using Android's {@link android.graphics.BitmapFactory}, based on the Skia library. This
* works well in most circumstances and has reasonable performance, however it has some problems
* with grayscale, indexed and CMYK images.
*/
public class SkiaImageDecoder implements ImageDecoder {
private static final String FILE_PREFIX = "file://";
private static final String ASSET_PREFIX = FILE_PREFIX + "/android_asset/";
private static final String RESOURCE_PREFIX = ContentResolver.SCHEME_ANDROID_RESOURCE + "://";
private final Bitmap.Config bitmapConfig;
@Keep
@SuppressWarnings("unused")
public SkiaImageDecoder() {
this(null);
}
@SuppressWarnings({"WeakerAccess", "SameParameterValue"})
public SkiaImageDecoder(@Nullable Bitmap.Config bitmapConfig) {
Bitmap.Config globalBitmapConfig = SubsamplingScaleImageView.getPreferredBitmapConfig();
if (bitmapConfig != null) {
this.bitmapConfig = bitmapConfig;
} else if (globalBitmapConfig != null) {
this.bitmapConfig = globalBitmapConfig;
} else {
this.bitmapConfig = Bitmap.Config.RGB_565;
}
}
@Override
@NonNull
public Bitmap decode(Context context, @NonNull Uri uri) throws Exception {
String uriString = uri.toString();
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap;
options.inPreferredConfig = bitmapConfig;
if (uriString.startsWith(RESOURCE_PREFIX)) {
Resources res;
String packageName = uri.getAuthority();
if (context.getPackageName().equals(packageName)) {
res = context.getResources();
} else {
PackageManager pm = context.getPackageManager();
res = pm.getResourcesForApplication(packageName);
}
int id = 0;
List segments = uri.getPathSegments();
int size = segments.size();
if (size == 2 && segments.get(0).equals("drawable")) {
String resName = segments.get(1);
id = res.getIdentifier(resName, "drawable", packageName);
} else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
try {
id = Integer.parseInt(segments.get(0));
} catch (NumberFormatException ignored) {
}
}
bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
} else if (uriString.startsWith(ASSET_PREFIX)) {
String assetName = uriString.substring(ASSET_PREFIX.length());
bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options);
} else if (uriString.startsWith(FILE_PREFIX)) {
bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options);
} else {
InputStream inputStream = null;
try {
ContentResolver contentResolver = context.getContentResolver();
inputStream = contentResolver.openInputStream(uri);
bitmap = BitmapFactory.decodeStream(inputStream, null, options);
} finally {
if (inputStream != null) {
try { inputStream.close(); } catch (Exception e) { /* Ignore */ }
}
}
}
if (bitmap == null) {
throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
}
return bitmap;
}
}
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/decoder/SkiaImageRegionDecoder.java
================================================
package com.davemorrissey.labs.subscaleview.decoder;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.*;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Default implementation of {@link com.davemorrissey.labs.subscaleview.decoder.ImageRegionDecoder}
* using Android's {@link android.graphics.BitmapRegionDecoder}, based on the Skia library. This
* works well in most circumstances and has reasonable performance due to the cached decoder instance,
* however it has some problems with grayscale, indexed and CMYK images.
*
* A {@link ReadWriteLock} is used to delegate responsibility for multi threading behaviour to the
* {@link BitmapRegionDecoder} instance on SDK >= 21, whilst allowing this class to block until no
* tiles are being loaded before recycling the decoder. In practice, {@link BitmapRegionDecoder} is
* synchronized internally so this has no real impact on performance.
*/
public class SkiaImageRegionDecoder implements ImageRegionDecoder {
private BitmapRegionDecoder decoder;
private final ReadWriteLock decoderLock = new ReentrantReadWriteLock(true);
private static final String FILE_PREFIX = "file://";
private static final String ASSET_PREFIX = FILE_PREFIX + "/android_asset/";
private static final String RESOURCE_PREFIX = ContentResolver.SCHEME_ANDROID_RESOURCE + "://";
private final Bitmap.Config bitmapConfig;
@Keep
@SuppressWarnings("unused")
public SkiaImageRegionDecoder() {
this(null);
}
@SuppressWarnings({"WeakerAccess", "SameParameterValue"})
public SkiaImageRegionDecoder(@Nullable Bitmap.Config bitmapConfig) {
Bitmap.Config globalBitmapConfig = SubsamplingScaleImageView.getPreferredBitmapConfig();
if (bitmapConfig != null) {
this.bitmapConfig = bitmapConfig;
} else if (globalBitmapConfig != null) {
this.bitmapConfig = globalBitmapConfig;
} else {
this.bitmapConfig = Bitmap.Config.RGB_565;
}
}
@Override
@NonNull
public Point init(Context context, @NonNull Uri uri) throws Exception {
String uriString = uri.toString();
if (uriString.startsWith(RESOURCE_PREFIX)) {
Resources res;
String packageName = uri.getAuthority();
if (context.getPackageName().equals(packageName)) {
res = context.getResources();
} else {
PackageManager pm = context.getPackageManager();
res = pm.getResourcesForApplication(packageName);
}
int id = 0;
List segments = uri.getPathSegments();
int size = segments.size();
if (size == 2 && segments.get(0).equals("drawable")) {
String resName = segments.get(1);
id = res.getIdentifier(resName, "drawable", packageName);
} else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
try {
id = Integer.parseInt(segments.get(0));
} catch (NumberFormatException ignored) {
}
}
decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
} else if (uriString.startsWith(ASSET_PREFIX)) {
String assetName = uriString.substring(ASSET_PREFIX.length());
decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
} else if (uriString.startsWith(FILE_PREFIX)) {
decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
} else {
InputStream inputStream = null;
try {
ContentResolver contentResolver = context.getContentResolver();
inputStream = contentResolver.openInputStream(uri);
if (inputStream == null) {
throw new Exception("Content resolver returned null stream. Unable to initialise with uri.");
}
decoder = BitmapRegionDecoder.newInstance(inputStream, false);
} finally {
if (inputStream != null) {
try { inputStream.close(); } catch (Exception e) { /* Ignore */ }
}
}
}
return new Point(decoder.getWidth(), decoder.getHeight());
}
@Override
@NonNull
public Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize) {
getDecodeLock().lock();
try {
if (decoder != null && !decoder.isRecycled()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
options.inPreferredConfig = bitmapConfig;
Bitmap bitmap = decoder.decodeRegion(sRect, options);
if (bitmap == null) {
throw new RuntimeException("Skia image decoder returned null bitmap - image format may not be supported");
}
return bitmap;
} else {
throw new IllegalStateException("Cannot decode region after decoder has been recycled");
}
} finally {
getDecodeLock().unlock();
}
}
@Override
public synchronized boolean isReady() {
return decoder != null && !decoder.isRecycled();
}
@Override
public synchronized void recycle() {
decoderLock.writeLock().lock();
try {
decoder.recycle();
decoder = null;
} finally {
decoderLock.writeLock().unlock();
}
}
/**
* Before SDK 21, BitmapRegionDecoder was not synchronized internally. Any attempt to decode
* regions from multiple threads with one decoder instance causes a segfault. For old versions
* use the write lock to enforce single threaded decoding.
*/
private Lock getDecodeLock() {
if (Build.VERSION.SDK_INT < 21) {
return decoderLock.writeLock();
} else {
return decoderLock.readLock();
}
}
}
================================================
FILE: library/src/main/java/com/davemorrissey/labs/subscaleview/decoder/SkiaPooledImageRegionDecoder.java
================================================
package com.davemorrissey.labs.subscaleview.decoder;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import java.io.File;
import java.io.FileFilter;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.regex.Pattern;
import static android.content.Context.ACTIVITY_SERVICE;
/**
*
* An implementation of {@link ImageRegionDecoder} using a pool of {@link BitmapRegionDecoder}s,
* to provide true parallel loading of tiles. This is only effective if parallel loading has been
* enabled in the view by calling {@link com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView#setExecutor(Executor)}
* with a multi-threaded {@link Executor} instance.
*
* One decoder is initialised when the class is initialised. This is enough to decode base layer tiles.
* Additional decoders are initialised when a subregion of the image is first requested, which indicates
* interaction with the view. Creation of additional encoders stops when {@link #allowAdditionalDecoder(int, long)}
* returns false. The default implementation takes into account the file size, number of CPU cores,
* low memory status and a hard limit of 4. Extend this class to customise this.
*
* WARNING: This class is highly experimental and not proven to be stable on a wide range of
* devices. You are advised to test it thoroughly on all available devices, and code your app to use
* {@link SkiaImageRegionDecoder} on old or low powered devices you could not test.
*
*/
public class SkiaPooledImageRegionDecoder implements ImageRegionDecoder {
private static final String TAG = SkiaPooledImageRegionDecoder.class.getSimpleName();
private static boolean debug = false;
private DecoderPool decoderPool = new DecoderPool();
private final ReadWriteLock decoderLock = new ReentrantReadWriteLock(true);
private static final String FILE_PREFIX = "file://";
private static final String ASSET_PREFIX = FILE_PREFIX + "/android_asset/";
private static final String RESOURCE_PREFIX = ContentResolver.SCHEME_ANDROID_RESOURCE + "://";
private final Bitmap.Config bitmapConfig;
private Context context;
private Uri uri;
private long fileLength = Long.MAX_VALUE;
private final Point imageDimensions = new Point(0, 0);
private final AtomicBoolean lazyInited = new AtomicBoolean(false);
@Keep
@SuppressWarnings("unused")
public SkiaPooledImageRegionDecoder() {
this(null);
}
@SuppressWarnings({"WeakerAccess", "SameParameterValue"})
public SkiaPooledImageRegionDecoder(@Nullable Bitmap.Config bitmapConfig) {
Bitmap.Config globalBitmapConfig = SubsamplingScaleImageView.getPreferredBitmapConfig();
if (bitmapConfig != null) {
this.bitmapConfig = bitmapConfig;
} else if (globalBitmapConfig != null) {
this.bitmapConfig = globalBitmapConfig;
} else {
this.bitmapConfig = Bitmap.Config.RGB_565;
}
}
/**
* Controls logging of debug messages. All instances are affected.
* @param debug true to enable debug logging, false to disable.
*/
@Keep
@SuppressWarnings("unused")
public static void setDebug(boolean debug) {
SkiaPooledImageRegionDecoder.debug = debug;
}
/**
* Initialises the decoder pool. This method creates one decoder on the current thread and uses
* it to decode the bounds, then spawns an independent thread to populate the pool with an
* additional three decoders. The thread will abort if {@link #recycle()} is called.
*/
@Override
@NonNull
public Point init(final Context context, @NonNull final Uri uri) throws Exception {
this.context = context;
this.uri = uri;
initialiseDecoder();
return this.imageDimensions;
}
/**
* Initialises extra decoders for as long as {@link #allowAdditionalDecoder(int, long)} returns
* true and the pool has not been recycled.
*/
private void lazyInit() {
if (lazyInited.compareAndSet(false, true) && fileLength < Long.MAX_VALUE) {
debug("Starting lazy init of additional decoders");
Thread thread = new Thread() {
@Override
public void run() {
while (decoderPool != null && allowAdditionalDecoder(decoderPool.size(), fileLength)) {
// New decoders can be created while reading tiles but this read lock prevents
// them being initialised while the pool is being recycled.
try {
if (decoderPool != null) {
long start = System.currentTimeMillis();
debug("Starting decoder");
initialiseDecoder();
long end = System.currentTimeMillis();
debug("Started decoder, took " + (end - start) + "ms");
}
} catch (Exception e) {
// A decoder has already been successfully created so we can ignore this
debug("Failed to start decoder: " + e.getMessage());
}
}
}
};
thread.start();
}
}
/**
* Initialises a new {@link BitmapRegionDecoder} and adds it to the pool, unless the pool has
* been recycled while it was created.
*/
private void initialiseDecoder() throws Exception {
String uriString = uri.toString();
BitmapRegionDecoder decoder;
long fileLength = Long.MAX_VALUE;
if (uriString.startsWith(RESOURCE_PREFIX)) {
Resources res;
String packageName = uri.getAuthority();
if (context.getPackageName().equals(packageName)) {
res = context.getResources();
} else {
PackageManager pm = context.getPackageManager();
res = pm.getResourcesForApplication(packageName);
}
int id = 0;
List segments = uri.getPathSegments();
int size = segments.size();
if (size == 2 && segments.get(0).equals("drawable")) {
String resName = segments.get(1);
id = res.getIdentifier(resName, "drawable", packageName);
} else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
try {
id = Integer.parseInt(segments.get(0));
} catch (NumberFormatException ignored) {
}
}
try {
AssetFileDescriptor descriptor = context.getResources().openRawResourceFd(id);
fileLength = descriptor.getLength();
} catch (Exception e) {
// Pooling disabled
}
decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
} else if (uriString.startsWith(ASSET_PREFIX)) {
String assetName = uriString.substring(ASSET_PREFIX.length());
try {
AssetFileDescriptor descriptor = context.getAssets().openFd(assetName);
fileLength = descriptor.getLength();
} catch (Exception e) {
// Pooling disabled
}
decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
} else if (uriString.startsWith(FILE_PREFIX)) {
decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
try {
File file = new File(uriString);
if (file.exists()) {
fileLength = file.length();
}
} catch (Exception e) {
// Pooling disabled
}
} else {
InputStream inputStream = null;
try {
ContentResolver contentResolver = context.getContentResolver();
inputStream = contentResolver.openInputStream(uri);
decoder = BitmapRegionDecoder.newInstance(inputStream, false);
try {
AssetFileDescriptor descriptor = contentResolver.openAssetFileDescriptor(uri, "r");
if (descriptor != null) {
fileLength = descriptor.getLength();
}
} catch (Exception e) {
// Stick with MAX_LENGTH
}
} finally {
if (inputStream != null) {
try { inputStream.close(); } catch (Exception e) { /* Ignore */ }
}
}
}
this.fileLength = fileLength;
this.imageDimensions.set(decoder.getWidth(), decoder.getHeight());
decoderLock.writeLock().lock();
try {
if (decoderPool != null) {
decoderPool.add(decoder);
}
} finally {
decoderLock.writeLock().unlock();
}
}
/**
* Acquire a read lock to prevent decoding overlapping with recycling, then check the pool still
* exists and acquire a decoder to load the requested region. There is no check whether the pool
* currently has decoders, because it's guaranteed to have one decoder after {@link #init(Context, Uri)}
* is called and be null once {@link #recycle()} is called. In practice the view can't call this
* method until after {@link #init(Context, Uri)}, so there will be no blocking on an empty pool.
*/
@Override
@NonNull
public Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize) {
debug("Decode region " + sRect + " on thread " + Thread.currentThread().getName());
if (sRect.width() < imageDimensions.x || sRect.height() < imageDimensions.y) {
lazyInit();
}
decoderLock.readLock().lock();
try {
if (decoderPool != null) {
BitmapRegionDecoder decoder = decoderPool.acquire();
try {
// Decoder can't be null or recycled in practice
if (decoder != null && !decoder.isRecycled()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
options.inPreferredConfig = bitmapConfig;
Bitmap bitmap = decoder.decodeRegion(sRect, options);
if (bitmap == null) {
throw new RuntimeException("Skia image decoder returned null bitmap - image format may not be supported");
}
return bitmap;
}
} finally {
if (decoder != null) {
decoderPool.release(decoder);
}
}
}
throw new IllegalStateException("Cannot decode region after decoder has been recycled");
} finally {
decoderLock.readLock().unlock();
}
}
/**
* Holding a read lock to avoid returning true while the pool is being recycled, this returns
* true if the pool has at least one decoder available.
*/
@Override
public synchronized boolean isReady() {
return decoderPool != null && !decoderPool.isEmpty();
}
/**
* Wait until all read locks held by {@link #decodeRegion(Rect, int)} are released, then recycle
* and destroy the pool. Elsewhere, when a read lock is acquired, we must check the pool is not null.
*/
@Override
public synchronized void recycle() {
decoderLock.writeLock().lock();
try {
if (decoderPool != null) {
decoderPool.recycle();
decoderPool = null;
context = null;
uri = null;
}
} finally {
decoderLock.writeLock().unlock();
}
}
/**
* Called before creating a new decoder. Based on number of CPU cores, available memory, and the
* size of the image file, determines whether another decoder can be created. Subclasses can
* override and customise this.
* @param numberOfDecoders the number of decoders that have been created so far
* @param fileLength the size of the image file in bytes. Creating another decoder will use approximately this much native memory.
* @return true if another decoder can be created.
*/
@SuppressWarnings("WeakerAccess")
protected boolean allowAdditionalDecoder(int numberOfDecoders, long fileLength) {
if (numberOfDecoders >= 4) {
debug("No additional decoders allowed, reached hard limit (4)");
return false;
} else if (numberOfDecoders * fileLength > 20 * 1024 * 1024) {
debug("No additional encoders allowed, reached hard memory limit (20Mb)");
return false;
} else if (numberOfDecoders >= getNumberOfCores()) {
debug("No additional encoders allowed, limited by CPU cores (" + getNumberOfCores() + ")");
return false;
} else if (isLowMemory()) {
debug("No additional encoders allowed, memory is low");
return false;
}
debug("Additional decoder allowed, current count is " + numberOfDecoders + ", estimated native memory " + ((fileLength * numberOfDecoders)/(1024 * 1024)) + "Mb");
return true;
}
/**
* A simple pool of {@link BitmapRegionDecoder} instances, all loading from the same source.
*/
private static class DecoderPool {
private final Semaphore available = new Semaphore(0, true);
private final Map decoders = new ConcurrentHashMap<>();
/**
* Returns false if there is at least one decoder in the pool.
*/
private synchronized boolean isEmpty() {
return decoders.isEmpty();
}
/**
* Returns number of encoders.
*/
private synchronized int size() {
return decoders.size();
}
/**
* Acquire a decoder. Blocks until one is available.
*/
private BitmapRegionDecoder acquire() {
available.acquireUninterruptibly();
return getNextAvailable();
}
/**
* Release a decoder back to the pool.
*/
private void release(BitmapRegionDecoder decoder) {
if (markAsUnused(decoder)) {
available.release();
}
}
/**
* Adds a newly created decoder to the pool, releasing an additional permit.
*/
private synchronized void add(BitmapRegionDecoder decoder) {
decoders.put(decoder, false);
available.release();
}
/**
* While there are decoders in the map, wait until each is available before acquiring,
* recycling and removing it. After this is called, any call to {@link #acquire()} will
* block forever, so this call should happen within a write lock, and all calls to
* {@link #acquire()} should be made within a read lock so they cannot end up blocking on
* the semaphore when it has no permits.
*/
private synchronized void recycle() {
while (!decoders.isEmpty()) {
BitmapRegionDecoder decoder = acquire();
decoder.recycle();
decoders.remove(decoder);
}
}
private synchronized BitmapRegionDecoder getNextAvailable() {
for (Map.Entry entry : decoders.entrySet()) {
if (!entry.getValue()) {
entry.setValue(true);
return entry.getKey();
}
}
return null;
}
private synchronized boolean markAsUnused(BitmapRegionDecoder decoder) {
for (Map.Entry entry : decoders.entrySet()) {
if (decoder == entry.getKey()) {
if (entry.getValue()) {
entry.setValue(false);
return true;
} else {
return false;
}
}
}
return false;
}
}
private int getNumberOfCores() {
if (Build.VERSION.SDK_INT >= 17) {
return Runtime.getRuntime().availableProcessors();
} else {
return getNumCoresOldPhones();
}
}
/**
* Gets the number of cores available in this device, across all processors.
* Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
* @return The number of cores, or 1 if failed to get result
*/
private int getNumCoresOldPhones() {
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return Pattern.matches("cpu[0-9]+", pathname.getName());
}
}
try {
File dir = new File("/sys/devices/system/cpu/");
File[] files = dir.listFiles(new CpuFilter());
return files.length;
} catch(Exception e) {
return 1;
}
}
private boolean isLowMemory() {
ActivityManager activityManager = (ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
if (activityManager != null) {
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
return memoryInfo.lowMemory;
} else {
return true;
}
}
private void debug(String message) {
if (debug) {
Log.d(TAG, message);
}
}
}
================================================
FILE: library/src/main/res/values/attrs.xml
================================================
================================================
FILE: release.gradle
================================================
apply plugin: 'maven'
apply plugin: 'signing'
def isReleaseBuild() {
return version.contains("SNAPSHOT") == false
}
def getMavenRepositoryUrl() {
return hasProperty('repositoryUrl') ? property('repositoryUrl') : "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
}
def getMavenRepositoryUsername() {
return hasProperty('sonatypeUsername') ? property('sonatypeUsername') : ""
}
def getMavenRepositoryPassword() {
return hasProperty('sonatypePassword') ? property('sonatypePassword') : ""
}
afterEvaluate { project ->
signing {
required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
sign configurations.archives
}
uploadArchives {
configuration = configurations.archives
repositories.mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
authentication(userName: getMavenRepositoryUsername(), password: getMavenRepositoryPassword())
}
pom.project {
name 'SubsamplingScaleImageView'
packaging 'aar'
description 'Highly configurable, easily extendable deep zoom view for displaying huge images without loss of detail. Perfect for photo galleries, maps, building plans etc.'
url 'https://github.com/davemorrissey/subsampling-scale-image-view'
scm {
url 'scm:git@github.com:davemorrissey/subsampling-scale-image-view.git'
connection 'scm:git@github.com:davemorrissey/subsampling-scale-image-view.git'
developerConnection 'scm:git@github.com:davemorrissey/subsampling-scale-image-view.git'
}
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution 'repo'
}
}
developers {
developer {
id 'davemorrissey'
name 'Dave Morrissey'
}
}
}
}
}
task androidJavadocs(type: Javadoc) {
onlyIf { gradle.taskGraph.hasTask("uploadArchives") }
source = android.sourceSets.main.java.sourceFiles
destinationDir = rootProject.file("docs/javadoc")
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
classpath += configurations.compile
classpath += configurations.javadocs
options.noTimestamp = true
options.links = ['https://developer.android.com/reference/']
}
task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
classifier = 'javadoc'
from androidJavadocs.destinationDir
}
task androidSourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.sourceFiles
}
artifacts {
archives androidSourcesJar
archives androidJavadocsJar
}
}
================================================
FILE: sample/build.gradle
================================================
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
defaultConfig {
minSdkVersion 17
targetSdkVersion 27
applicationId "com.davemorrissey.labs.subscaleview.test"
}
sourceSets {
main {
assets.srcDirs = ['assets']
}
}
}
dependencies {
implementation project(':library')
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
}
================================================
FILE: sample/src/main/AndroidManifest.xml
================================================
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/AbstractFragmentsActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test;
import android.app.ActionBar;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import android.view.MenuItem;
import java.util.List;
public abstract class AbstractFragmentsActivity extends FragmentActivity {
private static final String BUNDLE_PAGE = "page";
private int page;
private final int title;
private final int layout;
private final List notes;
protected abstract void onPageChanged(int page);
protected AbstractFragmentsActivity(int title, int layout, List notes) {
this.title = title;
this.layout = layout;
this.notes = notes;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.setTitle(getString(title));
actionBar.setDisplayHomeAsUpEnabled(true);
}
if (savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_PAGE)) {
page = savedInstanceState.getInt(BUNDLE_PAGE);
}
}
@Override
protected void onResume() {
super.onResume();
updateNotes();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(BUNDLE_PAGE, page);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
finish();
return true;
}
public void next() {
page++;
updateNotes();
}
public void previous() {
page--;
updateNotes();
}
private void updateNotes() {
if (page > notes.size() - 1) {
return;
}
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.setSubtitle(notes.get(page).getSubtitle());
}
onPageChanged(page);
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/AbstractPagesActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test;
import android.app.ActionBar;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import java.util.List;
public abstract class AbstractPagesActivity extends FragmentActivity {
private static final String BUNDLE_PAGE = "page";
private int page;
private final int title;
private final int layout;
private final List notes;
protected AbstractPagesActivity(int title, int layout, List notes) {
this.title = title;
this.layout = layout;
this.notes = notes;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.setTitle(getString(title));
actionBar.setDisplayHomeAsUpEnabled(true);
}
findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { next(); }
});
findViewById(R.id.previous).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { previous(); }
});
if (savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_PAGE)) {
page = savedInstanceState.getInt(BUNDLE_PAGE);
}
}
@Override
protected void onResume() {
super.onResume();
updateNotes();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(BUNDLE_PAGE, page);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
finish();
return true;
}
private void next() {
page++;
updateNotes();
}
private void previous() {
page--;
updateNotes();
}
private void updateNotes() {
if (page > notes.size() - 1) {
return;
}
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.setSubtitle(notes.get(page).getSubtitle());
}
((TextView)findViewById(R.id.note)).setText(notes.get(page).getText());
findViewById(R.id.next).setVisibility(page >= notes.size() - 1 ? View.INVISIBLE : View.VISIBLE);
findViewById(R.id.previous).setVisibility(page <= 0 ? View.INVISIBLE : View.VISIBLE);
onPageChanged(page);
}
protected final int getPage() {
return page;
}
protected void onPageChanged(int page) {
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/MainActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.animation.AnimationActivity;
import com.davemorrissey.labs.subscaleview.test.basicfeatures.BasicFeaturesActivity;
import com.davemorrissey.labs.subscaleview.test.configuration.ConfigurationActivity;
import com.davemorrissey.labs.subscaleview.test.eventhandling.EventHandlingActivity;
import com.davemorrissey.labs.subscaleview.test.eventhandlingadvanced.AdvancedEventHandlingActivity;
import com.davemorrissey.labs.subscaleview.test.extension.ExtensionActivity;
import com.davemorrissey.labs.subscaleview.test.imagedisplay.ImageDisplayActivity;
import com.davemorrissey.labs.subscaleview.test.viewpager.ViewPagerActivity;
public class MainActivity extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.main_title);
}
setContentView(R.layout.main);
findViewById(id.basicFeatures).setOnClickListener(this);
findViewById(id.imageDisplay).setOnClickListener(this);
findViewById(id.eventHandling).setOnClickListener(this);
findViewById(id.advancedEventHandling).setOnClickListener(this);
findViewById(id.viewPagerGalleries).setOnClickListener(this);
findViewById(id.animation).setOnClickListener(this);
findViewById(id.extension).setOnClickListener(this);
findViewById(id.configuration).setOnClickListener(this);
findViewById(id.github).setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case id.basicFeatures: startActivity(BasicFeaturesActivity.class); break;
case id.imageDisplay: startActivity(ImageDisplayActivity.class); break;
case id.eventHandling: startActivity(EventHandlingActivity.class); break;
case id.advancedEventHandling: startActivity(AdvancedEventHandlingActivity.class); break;
case id.viewPagerGalleries: startActivity(ViewPagerActivity.class); break;
case id.animation: startActivity(AnimationActivity.class); break;
case id.extension: startActivity(ExtensionActivity.class); break;
case id.configuration: startActivity(ConfigurationActivity.class); break;
case id.github: openGitHub(); break;
}
}
private void startActivity(Class extends Activity> activity) {
Intent intent = new Intent(this, activity);
startActivity(intent);
}
private void openGitHub() {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://github.com/davemorrissey/subsampling-scale-image-view"));
startActivity(i);
}
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/Page.java
================================================
package com.davemorrissey.labs.subscaleview.test;
public class Page {
private final int text;
private final int subtitle;
public Page(int subtitle, int text) {
this.subtitle = subtitle;
this.text = text;
}
public int getText() {
return text;
}
public int getSubtitle() {
return subtitle;
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/animation/AnimationActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test.animation;
import android.graphics.PointF;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.View;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView.AnimationBuilder;
import com.davemorrissey.labs.subscaleview.test.AbstractPagesActivity;
import com.davemorrissey.labs.subscaleview.test.Page;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.extension.views.PinView;
import java.util.Arrays;
import java.util.Random;
import static com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView.*;
import static com.davemorrissey.labs.subscaleview.test.R.string.*;
import static com.davemorrissey.labs.subscaleview.test.R.layout.*;
public class AnimationActivity extends AbstractPagesActivity {
private PinView view;
public AnimationActivity() {
super(animation_title, animation_activity, Arrays.asList(
new Page(animation_p1_subtitle, animation_p1_text),
new Page(animation_p2_subtitle, animation_p2_text),
new Page(animation_p3_subtitle, animation_p3_text),
new Page(animation_p4_subtitle, animation_p4_text)
));
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(id.play).setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) { AnimationActivity.this.play(); }
});
view = findViewById(id.imageView);
view.setImage(ImageSource.asset("sanmartino.jpg"));
}
@Override
protected void onPageChanged(int page) {
if (page == 2) {
view.setPanLimit(PAN_LIMIT_CENTER);
} else {
view.setPanLimit(PAN_LIMIT_INSIDE);
}
}
private void play() {
Random random = new Random();
if (view.isReady()) {
float maxScale = view.getMaxScale();
float minScale = view.getMinScale();
float scale = (random.nextFloat() * (maxScale - minScale)) + minScale;
PointF center = new PointF(random.nextInt(view.getSWidth()), random.nextInt(view.getSHeight()));
view.setPin(center);
AnimationBuilder animationBuilder = view.animateScaleAndCenter(scale, center);
if (getPage() == 3) {
animationBuilder.withDuration(2000).withEasing(EASE_OUT_QUAD).withInterruptible(false).start();
} else {
animationBuilder.withDuration(750).start();
}
}
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/basicfeatures/BasicFeaturesActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test.basicfeatures;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.test.AbstractPagesActivity;
import com.davemorrissey.labs.subscaleview.test.Page;
import com.davemorrissey.labs.subscaleview.test.R.id;
import java.util.Arrays;
import static com.davemorrissey.labs.subscaleview.test.R.string.*;
import static com.davemorrissey.labs.subscaleview.test.R.layout.*;
public class BasicFeaturesActivity extends AbstractPagesActivity {
public BasicFeaturesActivity() {
super(basic_title, pages_activity, Arrays.asList(
new Page(basic_p1_subtitle, basic_p1_text),
new Page(basic_p2_subtitle, basic_p2_text),
new Page(basic_p3_subtitle, basic_p3_text),
new Page(basic_p4_subtitle, basic_p4_text),
new Page(basic_p5_subtitle, basic_p5_text)
));
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SubsamplingScaleImageView view = findViewById(id.imageView);
view.setImage(ImageSource.asset("sanmartino.jpg"));
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/configuration/ConfigurationActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test.configuration;
import android.graphics.PointF;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.test.AbstractPagesActivity;
import com.davemorrissey.labs.subscaleview.test.Page;
import com.davemorrissey.labs.subscaleview.test.R.id;
import java.util.Arrays;
import static com.davemorrissey.labs.subscaleview.test.R.string.*;
import static com.davemorrissey.labs.subscaleview.test.R.layout.*;
public class ConfigurationActivity extends AbstractPagesActivity {
private SubsamplingScaleImageView view;
public ConfigurationActivity() {
super(configuration_title, pages_activity, Arrays.asList(
new Page(configuration_p1_subtitle, configuration_p1_text),
new Page(configuration_p2_subtitle, configuration_p2_text),
new Page(configuration_p3_subtitle, configuration_p3_text),
new Page(configuration_p4_subtitle, configuration_p4_text),
new Page(configuration_p5_subtitle, configuration_p5_text),
new Page(configuration_p6_subtitle, configuration_p6_text),
new Page(configuration_p7_subtitle, configuration_p7_text),
new Page(configuration_p8_subtitle, configuration_p8_text),
new Page(configuration_p9_subtitle, configuration_p9_text),
new Page(configuration_p10_subtitle, configuration_p10_text)
));
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = findViewById(id.imageView);
view.setImage(ImageSource.asset("card.png"));
}
@Override
protected void onPageChanged(int page) {
if (page == 0) {
view.setMinimumDpi(50);
} else {
view.setMaxScale(2F);
}
if (page == 1) {
view.setMinimumTileDpi(50);
} else {
view.setMinimumTileDpi(320);
}
if (page == 4) {
view.setDoubleTapZoomStyle(SubsamplingScaleImageView.ZOOM_FOCUS_CENTER);
} else if (page == 5) {
view.setDoubleTapZoomStyle(SubsamplingScaleImageView.ZOOM_FOCUS_CENTER_IMMEDIATE);
} else {
view.setDoubleTapZoomStyle(SubsamplingScaleImageView.ZOOM_FOCUS_FIXED);
}
if (page == 6) {
view.setDoubleTapZoomDpi(240);
} else {
view.setDoubleTapZoomScale(1F);
}
if (page == 7) {
view.setPanLimit(SubsamplingScaleImageView.PAN_LIMIT_CENTER);
} else if (page == 8) {
view.setPanLimit(SubsamplingScaleImageView.PAN_LIMIT_OUTSIDE);
} else {
view.setPanLimit(SubsamplingScaleImageView.PAN_LIMIT_INSIDE);
}
if (page == 9) {
view.setDebug(true);
} else {
view.setDebug(false);
}
if (page == 2) {
view.setScaleAndCenter(0f, new PointF(3900, 3120));
view.setPanEnabled(false);
} else {
view.setPanEnabled(true);
}
if (page == 3) {
view.setScaleAndCenter(1f, new PointF(3900, 3120));
view.setZoomEnabled(false);
} else {
view.setZoomEnabled(true);
}
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/eventhandling/EventHandlingActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test.eventhandling;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.test.AbstractPagesActivity;
import com.davemorrissey.labs.subscaleview.test.Page;
import com.davemorrissey.labs.subscaleview.test.R.id;
import java.util.Arrays;
import static com.davemorrissey.labs.subscaleview.test.R.layout.*;
import static com.davemorrissey.labs.subscaleview.test.R.string.*;
public class EventHandlingActivity extends AbstractPagesActivity {
public EventHandlingActivity() {
super(event_title, pages_activity, Arrays.asList(
new Page(event_p1_subtitle, event_p1_text),
new Page(event_p2_subtitle, event_p2_text),
new Page(event_p3_subtitle, event_p3_text)
));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SubsamplingScaleImageView imageView = findViewById(id.imageView);
imageView.setImage(ImageSource.asset("sanmartino.jpg"));
imageView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_SHORT).show(); }
});
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override public boolean onLongClick(View v) { Toast.makeText(v.getContext(), "Long clicked", Toast.LENGTH_SHORT).show(); return true; }
});
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/eventhandlingadvanced/AdvancedEventHandlingActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test.eventhandlingadvanced;
import android.graphics.PointF;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.test.AbstractPagesActivity;
import com.davemorrissey.labs.subscaleview.test.Page;
import com.davemorrissey.labs.subscaleview.test.R.id;
import java.util.Arrays;
import static com.davemorrissey.labs.subscaleview.test.R.string.*;
import static com.davemorrissey.labs.subscaleview.test.R.layout.*;
public class AdvancedEventHandlingActivity extends AbstractPagesActivity {
public AdvancedEventHandlingActivity() {
super(advancedevent_title, pages_activity, Arrays.asList(
new Page(advancedevent_p1_subtitle, advancedevent_p1_text),
new Page(advancedevent_p2_subtitle, advancedevent_p2_text),
new Page(advancedevent_p3_subtitle, advancedevent_p3_text),
new Page(advancedevent_p4_subtitle, advancedevent_p4_text),
new Page(advancedevent_p5_subtitle, advancedevent_p5_text)
));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SubsamplingScaleImageView imageView = findViewById(id.imageView);
final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (imageView.isReady()) {
PointF sCoord = imageView.viewToSourceCoord(e.getX(), e.getY());
Toast.makeText(getApplicationContext(), "Single tap: " + ((int)sCoord.x) + ", " + ((int)sCoord.y), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Single tap: Image not ready", Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public void onLongPress(MotionEvent e) {
if (imageView.isReady()) {
PointF sCoord = imageView.viewToSourceCoord(e.getX(), e.getY());
Toast.makeText(getApplicationContext(), "Long press: " + ((int)sCoord.x) + ", " + ((int)sCoord.y), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Long press: Image not ready", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onDoubleTap(MotionEvent e) {
if (imageView.isReady()) {
PointF sCoord = imageView.viewToSourceCoord(e.getX(), e.getY());
Toast.makeText(getApplicationContext(), "Double tap: " + ((int)sCoord.x) + ", " + ((int)sCoord.y), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Double tap: Image not ready", Toast.LENGTH_SHORT).show();
}
return true;
}
});
imageView.setImage(ImageSource.asset("sanmartino.jpg"));
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return gestureDetector.onTouchEvent(motionEvent);
}
});
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/extension/ExtensionActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test.extension;
import androidx.fragment.app.Fragment;
import android.util.Log;
import com.davemorrissey.labs.subscaleview.test.AbstractFragmentsActivity;
import com.davemorrissey.labs.subscaleview.test.Page;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.imagedisplay.ImageDisplayActivity;
import java.util.Arrays;
import java.util.List;
import static com.davemorrissey.labs.subscaleview.test.R.layout.fragments_activity;
import static com.davemorrissey.labs.subscaleview.test.R.string.extension_p1_subtitle;
import static com.davemorrissey.labs.subscaleview.test.R.string.extension_p1_text;
import static com.davemorrissey.labs.subscaleview.test.R.string.extension_p2_subtitle;
import static com.davemorrissey.labs.subscaleview.test.R.string.extension_p2_text;
import static com.davemorrissey.labs.subscaleview.test.R.string.extension_p3_subtitle;
import static com.davemorrissey.labs.subscaleview.test.R.string.extension_p3_text;
import static com.davemorrissey.labs.subscaleview.test.R.string.extension_title;
public class ExtensionActivity extends AbstractFragmentsActivity {
private static final List> FRAGMENTS = Arrays.asList(
ExtensionPinFragment.class,
ExtensionCircleFragment.class,
ExtensionFreehandFragment.class
);
public ExtensionActivity() {
super(extension_title, fragments_activity, Arrays.asList(
new Page(extension_p1_subtitle, extension_p1_text),
new Page(extension_p2_subtitle, extension_p2_text),
new Page(extension_p3_subtitle, extension_p3_text)
));
}
@Override
protected void onPageChanged(int page) {
try {
getSupportFragmentManager()
.beginTransaction()
.replace(id.frame, FRAGMENTS.get(page).newInstance())
.commit();
} catch (Exception e) {
Log.e(ImageDisplayActivity.class.getName(), "Failed to load fragment", e);
}
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/extension/ExtensionCircleFragment.java
================================================
package com.davemorrissey.labs.subscaleview.test.extension;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.R.layout;
public class ExtensionCircleFragment extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(layout.extension_circle_fragment, container, false);
final ExtensionActivity activity = (ExtensionActivity)getActivity();
if (activity != null) {
rootView.findViewById(id.next).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { activity.next(); }
});
rootView.findViewById(id.previous).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { activity.previous(); }
});
}
SubsamplingScaleImageView imageView = rootView.findViewById(id.imageView);
imageView.setImage(ImageSource.asset("sanmartino.jpg"));
return rootView;
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/extension/ExtensionFreehandFragment.java
================================================
package com.davemorrissey.labs.subscaleview.test.extension;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.R.layout;
import com.davemorrissey.labs.subscaleview.test.extension.views.FreehandView;
public class ExtensionFreehandFragment extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(layout.extension_freehand_fragment, container, false);
final ExtensionActivity activity = (ExtensionActivity)getActivity();
if (activity != null) {
rootView.findViewById(id.previous).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { activity.previous(); }
});
}
final FreehandView imageView = rootView.findViewById(id.imageView);
imageView.setImage(ImageSource.asset("sanmartino.jpg"));
rootView.findViewById(id.reset).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { imageView.reset(); }
});
return rootView;
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/extension/ExtensionPinFragment.java
================================================
package com.davemorrissey.labs.subscaleview.test.extension;
import android.graphics.PointF;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.R.layout;
import com.davemorrissey.labs.subscaleview.test.extension.views.PinView;
public class ExtensionPinFragment extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(layout.extension_pin_fragment, container, false);
final ExtensionActivity activity = (ExtensionActivity)getActivity();
if (activity != null) {
rootView.findViewById(id.next).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { activity.next(); }
});
}
PinView imageView = rootView.findViewById(id.imageView);
imageView.setImage(ImageSource.asset("sanmartino.jpg"));
imageView.setPin(new PointF(1602f, 405f));
return rootView;
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/extension/views/CircleView.java
================================================
package com.davemorrissey.labs.subscaleview.test.extension.views;
import android.content.Context;
import android.graphics.*;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
public class CircleView extends SubsamplingScaleImageView {
private int strokeWidth;
private final PointF sCenter = new PointF();
private final PointF vCenter = new PointF();
private final Paint paint = new Paint();
public CircleView(Context context) {
this(context, null);
}
public CircleView(Context context, AttributeSet attr) {
super(context, attr);
initialise();
}
private void initialise() {
float density = getResources().getDisplayMetrics().densityDpi;
strokeWidth = (int)(density/60f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Don't draw pin before image is ready so it doesn't move around during setup.
if (!isReady()) {
return;
}
sCenter.set(getSWidth()/2, getSHeight()/2);
sourceToViewCoord(sCenter, vCenter);
float radius = (getScale() * getSWidth()) * 0.25f;
paint.setAntiAlias(true);
paint.setStyle(Style.STROKE);
paint.setStrokeCap(Cap.ROUND);
paint.setStrokeWidth(strokeWidth * 2);
paint.setColor(Color.BLACK);
canvas.drawCircle(vCenter.x, vCenter.y, radius, paint);
paint.setStrokeWidth(strokeWidth);
paint.setColor(Color.argb(255, 51, 181, 229));
canvas.drawCircle(vCenter.x, vCenter.y, radius, paint);
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/extension/views/FreehandView.java
================================================
package com.davemorrissey.labs.subscaleview.test.extension.views;
import android.content.Context;
import android.graphics.*;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Style;
import androidx.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import java.util.ArrayList;
import java.util.List;
public class FreehandView extends SubsamplingScaleImageView implements OnTouchListener {
private final Paint paint = new Paint();
private final Path vPath = new Path();
private final PointF vPoint = new PointF();
private PointF vPrev = new PointF();
private PointF vPrevious;
private PointF vStart;
private boolean drawing = false;
private int strokeWidth;
private List sPoints;
public FreehandView(Context context, AttributeSet attr) {
super(context, attr);
initialise();
}
public FreehandView(Context context) {
this(context, null);
}
private void initialise() {
setOnTouchListener(this);
float density = getResources().getDisplayMetrics().densityDpi;
strokeWidth = (int)(density/60f);
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
if (sPoints != null && !drawing) {
return super.onTouchEvent(event);
}
boolean consumed = false;
int touchCount = event.getPointerCount();
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
if (event.getActionIndex() == 0) {
vStart = new PointF(event.getX(), event.getY());
vPrevious = new PointF(event.getX(), event.getY());
} else {
vStart = null;
vPrevious = null;
}
break;
case MotionEvent.ACTION_MOVE:
PointF sCurrentF = viewToSourceCoord(event.getX(), event.getY());
PointF sCurrent = new PointF(sCurrentF.x, sCurrentF.y);
PointF sStart = vStart == null ? null : new PointF(viewToSourceCoord(vStart).x, viewToSourceCoord(vStart).y);
if (touchCount == 1 && vStart != null) {
float vDX = Math.abs(event.getX() - vPrevious.x);
float vDY = Math.abs(event.getY() - vPrevious.y);
if (vDX >= strokeWidth * 5 || vDY >= strokeWidth * 5) {
if (sPoints == null) {
sPoints = new ArrayList<>();
sPoints.add(sStart);
}
sPoints.add(sCurrent);
vPrevious.x = event.getX();
vPrevious.y = event.getY();
drawing = true;
}
consumed = true;
invalidate();
} else if (touchCount == 1) {
// Consume all one touch drags to prevent odd panning effects handled by the superclass.
consumed = true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
invalidate();
drawing = false;
vPrevious = null;
vStart = null;
}
// Use parent to handle pinch and two-finger pan.
return consumed || super.onTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Don't draw anything before image is ready.
if (!isReady()) {
return;
}
paint.setAntiAlias(true);
if (sPoints != null && sPoints.size() >= 2) {
vPath.reset();
sourceToViewCoord(sPoints.get(0).x, sPoints.get(0).y, vPrev);
vPath.moveTo(vPrev.x, vPrev.y);
for (int i = 1; i < sPoints.size(); i++) {
sourceToViewCoord(sPoints.get(i).x, sPoints.get(i).y, vPoint);
vPath.quadTo(vPrev.x, vPrev.y, (vPoint.x + vPrev.x) / 2, (vPoint.y + vPrev.y) / 2);
vPrev = vPoint;
}
paint.setStyle(Style.STROKE);
paint.setStrokeCap(Cap.ROUND);
paint.setStrokeWidth(strokeWidth * 2);
paint.setColor(Color.BLACK);
canvas.drawPath(vPath, paint);
paint.setStrokeWidth(strokeWidth);
paint.setColor(Color.argb(255, 51, 181, 229));
canvas.drawPath(vPath, paint);
}
}
public void reset() {
this.sPoints = null;
invalidate();
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/extension/views/PinView.java
================================================
package com.davemorrissey.labs.subscaleview.test.extension.views;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.test.R.drawable;
public class PinView extends SubsamplingScaleImageView {
private final Paint paint = new Paint();
private final PointF vPin = new PointF();
private PointF sPin;
private Bitmap pin;
public PinView(Context context) {
this(context, null);
}
public PinView(Context context, AttributeSet attr) {
super(context, attr);
initialise();
}
public void setPin(PointF sPin) {
this.sPin = sPin;
initialise();
invalidate();
}
private void initialise() {
float density = getResources().getDisplayMetrics().densityDpi;
pin = BitmapFactory.decodeResource(this.getResources(), drawable.pushpin_blue);
float w = (density/420f) * pin.getWidth();
float h = (density/420f) * pin.getHeight();
pin = Bitmap.createScaledBitmap(pin, (int)w, (int)h, true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Don't draw pin before image is ready so it doesn't move around during setup.
if (!isReady()) {
return;
}
paint.setAntiAlias(true);
if (sPin != null && pin != null) {
sourceToViewCoord(sPin, vPin);
float vX = vPin.x - (pin.getWidth()/2);
float vY = vPin.y - pin.getHeight();
canvas.drawBitmap(pin, vX, vY, paint);
}
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/imagedisplay/ImageDisplayActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test.imagedisplay;
import androidx.fragment.app.Fragment;
import android.util.Log;
import com.davemorrissey.labs.subscaleview.test.AbstractFragmentsActivity;
import com.davemorrissey.labs.subscaleview.test.Page;
import com.davemorrissey.labs.subscaleview.test.R.id;
import java.util.Arrays;
import java.util.List;
import static com.davemorrissey.labs.subscaleview.test.R.string.*;
import static com.davemorrissey.labs.subscaleview.test.R.layout.*;
public class ImageDisplayActivity extends AbstractFragmentsActivity {
private static final List> FRAGMENTS = Arrays.asList(
ImageDisplayLargeFragment.class,
ImageDisplayRotateFragment.class,
ImageDisplayRegionFragment.class
);
public ImageDisplayActivity() {
super(display_title, fragments_activity, Arrays.asList(
new Page(display_p1_subtitle, display_p1_text),
new Page(display_p2_subtitle, display_p2_text),
new Page(display_p3_subtitle, display_p3_text)
));
}
@Override
protected void onPageChanged(int page) {
try {
getSupportFragmentManager()
.beginTransaction()
.replace(id.frame, FRAGMENTS.get(page).newInstance())
.commit();
} catch (Exception e) {
Log.e(ImageDisplayActivity.class.getName(), "Failed to load fragment", e);
}
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/imagedisplay/ImageDisplayLargeFragment.java
================================================
package com.davemorrissey.labs.subscaleview.test.imagedisplay;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.R.layout;
public class ImageDisplayLargeFragment extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(layout.imagedisplay_large_fragment, container, false);
final ImageDisplayActivity activity = (ImageDisplayActivity)getActivity();
if (activity != null) {
rootView.findViewById(id.next).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { activity.next(); }
});
}
SubsamplingScaleImageView imageView = rootView.findViewById(id.imageView);
imageView.setImage(ImageSource.asset("card.png"));
return rootView;
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/imagedisplay/ImageDisplayRegionFragment.java
================================================
package com.davemorrissey.labs.subscaleview.test.imagedisplay;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.decoder.CompatDecoderFactory;
import com.davemorrissey.labs.subscaleview.decoder.ImageDecoder;
import com.davemorrissey.labs.subscaleview.decoder.ImageRegionDecoder;
import com.davemorrissey.labs.subscaleview.decoder.SkiaImageDecoder;
import com.davemorrissey.labs.subscaleview.decoder.SkiaImageRegionDecoder;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.R.layout;
public class ImageDisplayRegionFragment extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(layout.imagedisplay_region_fragment, container, false);
final SubsamplingScaleImageView imageView = rootView.findViewById(id.imageView);
imageView.setBitmapDecoderFactory(new CompatDecoderFactory(SkiaImageDecoder.class, Bitmap.Config.ARGB_8888));
imageView.setRegionDecoderFactory(new CompatDecoderFactory(SkiaImageRegionDecoder.class, Bitmap.Config.ARGB_8888));
imageView.setOrientation(SubsamplingScaleImageView.ORIENTATION_90);
imageView.setImage(ImageSource.asset("card.png").region(new Rect(5200, 651, 8200, 3250)));
final ImageDisplayActivity activity = (ImageDisplayActivity)getActivity();
if (activity != null) {
rootView.findViewById(id.previous).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { activity.previous(); }
});
}
rootView.findViewById(id.rotate).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { imageView.setOrientation((imageView.getOrientation() + 90) % 360); }
});
return rootView;
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/imagedisplay/ImageDisplayRotateFragment.java
================================================
package com.davemorrissey.labs.subscaleview.test.imagedisplay;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.R.layout;
public class ImageDisplayRotateFragment extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(layout.imagedisplay_rotate_fragment, container, false);
final SubsamplingScaleImageView imageView = rootView.findViewById(id.imageView);
imageView.setImage(ImageSource.asset("swissroad.jpg"));
imageView.setOrientation(90);
final ImageDisplayActivity activity = (ImageDisplayActivity)getActivity();
if (activity != null) {
rootView.findViewById(id.previous).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { activity.previous(); }
});
rootView.findViewById(id.next).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { activity.next(); }
});
}
rootView.findViewById(id.rotate).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { imageView.setOrientation((imageView.getOrientation() + 90) % 360); }
});
return rootView;
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/viewpager/VerticalViewPager.java
================================================
package com.davemorrissey.labs.subscaleview.test.viewpager;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* From http://stackoverflow.com/a/22797619/2719186
*/
public class VerticalViewPager extends ViewPager {
public VerticalViewPager(Context context) {
super(context);
init();
}
public VerticalViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setPageTransformer(true, new VerticalPageTransformer());
setOverScrollMode(OVER_SCROLL_NEVER);
}
private class VerticalPageTransformer implements ViewPager.PageTransformer {
@Override
public void transformPage(@NonNull View view, float position) {
if (position < -1) {
view.setAlpha(0);
} else if (position <= 1) {
view.setAlpha(1);
view.setTranslationX(view.getWidth() * -position);
float yPosition = position * view.getHeight();
view.setTranslationY(yPosition);
} else {
view.setAlpha(0);
}
}
}
private MotionEvent swapXY(MotionEvent ev) {
float width = getWidth();
float height = getHeight();
float newX = (ev.getY() / height) * width;
float newY = (ev.getX() / width) * height;
ev.setLocation(newX, newY);
return ev;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev){
boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
swapXY(ev);
return intercepted;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(swapXY(ev));
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/viewpager/ViewPagerActivity.java
================================================
package com.davemorrissey.labs.subscaleview.test.viewpager;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import com.davemorrissey.labs.subscaleview.test.AbstractPagesActivity;
import com.davemorrissey.labs.subscaleview.test.Page;
import com.davemorrissey.labs.subscaleview.test.R;
import java.util.Arrays;
import static com.davemorrissey.labs.subscaleview.test.R.layout.view_pager;
import static com.davemorrissey.labs.subscaleview.test.R.string.pager_p1_subtitle;
import static com.davemorrissey.labs.subscaleview.test.R.string.pager_p1_text;
import static com.davemorrissey.labs.subscaleview.test.R.string.pager_p2_subtitle;
import static com.davemorrissey.labs.subscaleview.test.R.string.pager_p2_text;
import static com.davemorrissey.labs.subscaleview.test.R.string.pager_title;
public class ViewPagerActivity extends AbstractPagesActivity {
private static final String[] IMAGES = { "sanmartino.jpg", "swissroad.jpg" };
public ViewPagerActivity() {
super(pager_title, view_pager, Arrays.asList(
new Page(pager_p1_subtitle, pager_p1_text),
new Page(pager_p2_subtitle, pager_p2_text)
));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewPager horizontalPager = findViewById(R.id.horizontal_pager);
horizontalPager.setAdapter(new ScreenSlidePagerAdapter(getSupportFragmentManager()));
ViewPager verticalPager = findViewById(R.id.vertical_pager);
verticalPager.setAdapter(new ScreenSlidePagerAdapter(getSupportFragmentManager()));
}
@Override
public void onBackPressed() {
ViewPager viewPager = findViewById(getPage() == 0 ? R.id.horizontal_pager : R.id.vertical_pager);
if (viewPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
@Override
protected void onPageChanged(int page) {
if (getPage() == 0) {
findViewById(R.id.horizontal_pager).setVisibility(View.VISIBLE);
findViewById(R.id.vertical_pager).setVisibility(View.GONE);
} else {
findViewById(R.id.horizontal_pager).setVisibility(View.GONE);
findViewById(R.id.vertical_pager).setVisibility(View.VISIBLE);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
ViewPagerFragment fragment = new ViewPagerFragment();
fragment.setAsset(IMAGES[position]);
return fragment;
}
@Override
public int getCount() {
return IMAGES.length;
}
}
}
================================================
FILE: sample/src/main/java/com/davemorrissey/labs/subscaleview/test/viewpager/ViewPagerFragment.java
================================================
package com.davemorrissey.labs.subscaleview.test.viewpager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.davemorrissey.labs.subscaleview.test.R.id;
import com.davemorrissey.labs.subscaleview.test.R.layout;
public class ViewPagerFragment extends Fragment {
private static final String BUNDLE_ASSET = "asset";
private String asset;
public ViewPagerFragment() {
}
public void setAsset(String asset) {
this.asset = asset;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(layout.view_pager_page, container, false);
if (savedInstanceState != null) {
if (asset == null && savedInstanceState.containsKey(BUNDLE_ASSET)) {
asset = savedInstanceState.getString(BUNDLE_ASSET);
}
}
if (asset != null) {
SubsamplingScaleImageView imageView = rootView.findViewById(id.imageView);
imageView.setImage(ImageSource.asset(asset));
}
return rootView;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
View rootView = getView();
if (rootView != null) {
outState.putString(BUNDLE_ASSET, asset);
}
}
}
================================================
FILE: sample/src/main/res/drawable-nodpi/button_standout_inactive.xml
================================================
================================================
FILE: sample/src/main/res/drawable-nodpi/button_standout_pressed.xml
================================================
================================================
FILE: sample/src/main/res/drawable-nodpi/button_transparent_pressed.xml
================================================
================================================
FILE: sample/src/main/res/drawable-nodpi/buttonstate_standout.xml
================================================
================================================
FILE: sample/src/main/res/drawable-nodpi/buttonstate_transparent.xml
================================================
================================================
FILE: sample/src/main/res/drawable-nodpi/transparent.xml
================================================
================================================
FILE: sample/src/main/res/layout/animation_activity.xml
================================================
================================================
FILE: sample/src/main/res/layout/extension_circle_fragment.xml
================================================
================================================
FILE: sample/src/main/res/layout/extension_freehand_fragment.xml
================================================
================================================
FILE: sample/src/main/res/layout/extension_pin_fragment.xml
================================================
================================================
FILE: sample/src/main/res/layout/fragments_activity.xml
================================================
================================================
FILE: sample/src/main/res/layout/imagedisplay_large_fragment.xml
================================================
================================================
FILE: sample/src/main/res/layout/imagedisplay_region_fragment.xml
================================================
================================================
FILE: sample/src/main/res/layout/imagedisplay_rotate_fragment.xml
================================================
================================================
FILE: sample/src/main/res/layout/main.xml
================================================
================================================
FILE: sample/src/main/res/layout/pages_activity.xml
================================================
================================================
FILE: sample/src/main/res/layout/view_pager.xml
================================================
================================================
FILE: sample/src/main/res/layout/view_pager_page.xml
================================================
================================================
FILE: sample/src/main/res/values/colors.xml
================================================
#111111#282828
================================================
FILE: sample/src/main/res/values/strings.xml
================================================
SSIV Test AppSubsampling Scale Image ViewView on GitHubAnimateNextPreviousRotateResetBasic featuresBasic featuresPinch to zoom
Use a two finger pinch to zoom in and out. The zoom is centred on the pinch gesture, and you can pan at the same time.
Quick scale
Double tap and swipe up or down to zoom in or out. The zoom is centred where you tapped.
DragUse one finger to drag the image around.Fling
If you drag quickly and let go, fling momentum keeps the image moving.
Double tap
Double tap the image to zoom in to that spot. Double tap again to zoom out.
Image displayImage displayLarge images
This image is 7,800 x 6,240 pixels. On most devices it will be subsampled, and higher quality tiles are loaded as you zoom in.
Rotation
This image has been rotated 90 degrees. Tap the button to rotate it. EXIF rotation is supported for external files.
Display regionSet the region to display instead of the whole image.Event handlingEvent handlingSimple events
Touch handling by the image view doesn\'t prevent normal events from working.
OnClickListener
This view has an OnClickListener. Tap once to activate the click.
OnLongClickListener
This view has an OnLongClickListener. Press and hold to activate it.
Advanced event handlingAdvanced event handlingOverriding gesturesSome gestures can be overridden with your own
GestureDetector without affecting the image view. This allows you to get the coordinates of
the event.
onSingleTapConfirmedonSingleTapConfirmed has been overridden. Tap the image to
see coordinates.
onDoubleTaponDoubleTap has been overridden. Tap the image to see
coordinates. This overrides the default zoom in behaviour.
onLongPressonLongPress has been overridden. Press and hold the image
to see coordinates.
Other eventsYou can override any event you want, but customising swipe,
fling and zoom gestures will stop the view working normally.
View pager galleriesView pager galleryHorizontal
This gallery has two images in a ViewPager. Swipe to move to the
next image. If you\'re zoomed in on an image, you need to pan to the right of it, then swipe
again to activate the pager.
Vertical
Vertical view pagers are also supported. Swipe up to move to the
next image. If you\'re zoomed in on an image, you need to pan to the bottom of it, then
swipe again to activate the pager.
AnimationAnimationA demo
Tap the play button. The image will scale and zoom to a random point, shown by a marker.
Limited pan
If the target point is near the edge of the image, it will be moved as near to the center as possible.
Unlimited pan
With unlimited or center-limited pan, the target point can always be animated to the center.
Customisation
Duration and easing are configurable. You can also make animations non-interruptible.
ExtensionExtensionLocation pin
This view class extends the image view, and adds a pin anchored to a point on the image.
Overlaid circle
A slightly more advanced example, this shows a circle that will
move and scale with the image. (Due to a limitation in Android, this circle may disappear
when it\'s larger than 2048px.)
Freehand drawing
This subclass adds event detection. Draw a freehand line; it
will move with the image. (Due to a limitation in Android, your drawing may disappear when
it\'s larger than 2048px.)
ConfigurationConfigurationMaximum scale
The maximum scale has been set to 50dpi. You can zoom in until the image is very pixellated.
Minimum tile DPI
The minimum tile DPI has been set to 50dpi, to reduce
memory usage. The next layer of tiles will not be loaded until the image is very pixellated.
Pan disabled
Dragging has been disabled. You can only zoom in to the centre point.
Zoom disabled
Zooming has been disabled. You can drag the image around.
Double tap style
On double tap, the tapped point is now zoomed to the center of the screen instead of remaining in the same place.
Double tap styleOn double tap, the zoom now happens immediately.Double tap scaleThe double tap zoom scale has been set to 240dpi.Pan limit center
The pan limit has been changed to PAN_LIMIT_CENTER. Panning stops when a corner reaches the centre of the screen.
Pan limit outside
The pan limit has been changed to PAN_LIMIT_OUTSIDE. Panning stops when the image is just off screen.
Debug
Debug has been enabled. This shows the tile boundaries and sizes.
================================================
FILE: sample/src/main/res/values/style.xml
================================================
================================================
FILE: settings.gradle
================================================
include ':library'
include ':sample'