├── .gitignore ├── .idea ├── codeStyles │ └── Project.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── PRINCIPLE.md ├── README.md ├── app ├── .gitignore ├── build.gradle ├── myapp.keystore ├── proguard-rules.pro ├── release │ └── output.json └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── xuliwen │ │ └── zoom │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── xuliwen │ │ │ └── zoom │ │ │ └── demo │ │ │ ├── LongPictureActivity.java │ │ │ ├── MainActivity.java │ │ │ ├── MyPagerAdapter.java │ │ │ ├── ShortPictureActivity.java │ │ │ ├── SizeChangeActivity.java │ │ │ └── ViewPagerActivity.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── activity_size_change.xml │ │ ├── activity_view_pager.xml │ │ ├── layout_long_picture.xml │ │ ├── layout_other_picture.xml │ │ └── layout_short_picture.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_round.png │ │ ├── image1.jpg │ │ ├── image2.jpg │ │ ├── other.jpeg │ │ ├── short_pic.jpeg │ │ └── size_change.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── xuliwen │ └── zoom │ └── ExampleUnitTest.java ├── build.gradle ├── demofile ├── zoomLayout.apk └── zoomLayout.gif ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── xuliwen │ │ └── zoom │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── xuliwen │ │ │ └── zoom │ │ │ ├── ScaleHelper.java │ │ │ └── ZoomLayout.java │ └── res │ │ └── values │ │ ├── attr.xml │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── xuliwen │ └── zoom │ └── ExampleUnitTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Files for the ART/Dalvik VM 2 | *.dex 3 | 4 | # Java class files 5 | *.class 6 | 7 | # Generated files 8 | bin/ 9 | gen/ 10 | out/ 11 | 12 | # Gradle files 13 | .gradle/ 14 | build/ 15 | 16 | # Local configuration file (sdk path, etc) 17 | local.properties 18 | 19 | # Proguard folder generated by Eclipse 20 | proguard/ 21 | 22 | # Log Files 23 | *.log 24 | 25 | # Android Studio Navigation editor temp files 26 | .navigation/ 27 | 28 | # Android Studio captures folder 29 | captures/ 30 | 31 | # IntelliJ 32 | *.iml 33 | .idea/workspace.xml 34 | .idea/tasks.xml 35 | .idea/gradle.xml 36 | .idea/assetWizardSettings.xml 37 | .idea/dictionaries 38 | .idea/libraries 39 | .idea/caches 40 | 41 | # Keystore files 42 | # Uncomment the following line if you do not want to check your keystore files in. 43 | #*.jks 44 | 45 | # External native build folder generated in Android Studio 2.2 and later 46 | .externalNativeBuild 47 | 48 | # Google Services (e.g. APIs or Firebase) 49 | google-services.json 50 | 51 | # Freeline 52 | freeline.py 53 | freeline/ 54 | freeline_project_description.json 55 | 56 | # fastlane 57 | fastlane/report.xml 58 | fastlane/Preview.html 59 | fastlane/screenshots 60 | fastlane/test_output 61 | fastlane/readme.md 62 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | xmlns:android 14 | 15 | ^$ 16 | 17 | 18 | 19 |
20 |
21 | 22 | 23 | 24 | xmlns:.* 25 | 26 | ^$ 27 | 28 | 29 | BY_NAME 30 | 31 |
32 |
33 | 34 | 35 | 36 | .*:id 37 | 38 | http://schemas.android.com/apk/res/android 39 | 40 | 41 | 42 |
43 |
44 | 45 | 46 | 47 | .*:name 48 | 49 | http://schemas.android.com/apk/res/android 50 | 51 | 52 | 53 |
54 |
55 | 56 | 57 | 58 | name 59 | 60 | ^$ 61 | 62 | 63 | 64 |
65 |
66 | 67 | 68 | 69 | style 70 | 71 | ^$ 72 | 73 | 74 | 75 |
76 |
77 | 78 | 79 | 80 | .* 81 | 82 | ^$ 83 | 84 | 85 | BY_NAME 86 | 87 |
88 |
89 | 90 | 91 | 92 | .* 93 | 94 | http://schemas.android.com/apk/res/android 95 | 96 | 97 | ANDROID_ATTRIBUTE_ORDER 98 | 99 |
100 |
101 | 102 | 103 | 104 | .* 105 | 106 | .* 107 | 108 | 109 | BY_NAME 110 | 111 |
112 |
113 |
114 |
115 |
116 |
-------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PRINCIPLE.md: -------------------------------------------------------------------------------- 1 | ## 1. ZoomLayout 需要实现的功能 2 | 3 | ### 1.1 需求列表 4 | 5 | 1. 触摸滑动及惯性滑动 6 | 2. 多指缩放 7 | 3. 双击缩放 8 | 9 | 除了实现这些主要功能外,还需要处理一下的细节 10 | 1. ZoomLayout 的宽高大于子 View时,子 View 居中显示 11 | 2. ZoomLayout 需要响应事件,但是不能把事件拦截掉 12 | 3. 处理滑动冲突,比如将 ZoomLayout 放在 ViewPager 中 13 | 14 | 15 | 16 | ### 1.2 使用举例 17 | 18 | ``` 19 | 20 | 28 | 29 | 33 | 34 | 40 | 41 | 47 | 48 | 49 | ``` 50 | 51 | ### 1.3 效果和源码 52 | 53 | 效果如下: 54 | 55 | ![zoomlayout.gif](https://github.com/guangmomo/ZoomLayout/blob/master/demofile/zoomLayout.gif) 56 | 57 | ZoomLayout 源码 58 | [ZoomLayout 源码](https://github.com/guangmomo/ZoomLayout) 59 | 60 | 61 | 62 | ## 2. 实现 63 | 64 | ### 2.1 基础知识 65 | 66 | 在讲具体实现之前,先提一下会用到的一些基础的知识,不了解的同学可以先去了解一下 67 | 68 | 1. GestureDetector 用于获取单击、双击、滚动、抛掷 等动作 69 | 2. ScaleGestureDetector 用于获取缩放的动作 70 | 3. OverScroller 滚动的辅助类 71 | 72 | ### 2.2 重写 measureChildWithMargins 73 | 74 | ``` 75 | @Override 76 | protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 77 | int parentHeightMeasureSpec, int heightUsed) { 78 | final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 79 | 80 | final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 81 | getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin 82 | + widthUsed, lp.width); 83 | final int usedTotal = getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin + 84 | heightUsed; 85 | final int childHeightMeasureSpec; 86 | if (lp.height == WRAP_CONTENT) { 87 | childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( 88 | Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - usedTotal), 89 | MeasureSpec.UNSPECIFIED); 90 | } else { 91 | childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 92 | getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin 93 | + heightUsed, lp.height); 94 | } 95 | child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 96 | } 97 | ``` 98 | 99 | ZoomLayout 继承了 LinearLayout 后,发现屏幕外的 View 是没有绘制出来的,但是我们平时使用 ScrollView 的时候,屏幕外的 View 也能绘制出来,查看 ScrollView 的源码,发现它重写了 measureChildWithMargins 方法。 100 | 101 | ### 2.3 实现滚动 102 | 103 | 104 | ``` 105 | private GestureDetector.SimpleOnGestureListener mSimpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() { 106 | @Override 107 | public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 108 | if (!isEnabled()) { 109 | return false; 110 | } 111 | processScroll((int) distanceX, (int) distanceY, getScrollRangeX(), getScrollRangeY()); 112 | return true; 113 | } 114 | }; 115 | 116 | private void processScroll(int deltaX, int deltaY, 117 | int scrollRangeX, int scrollRangeY) { 118 | int oldScrollX = getScrollX(); 119 | int oldScrollY = getScrollY(); 120 | int newScrollX = oldScrollX + deltaX; 121 | int newScrollY = oldScrollY + deltaY; 122 | final int left = 0; 123 | final int right = scrollRangeX; 124 | final int top = 0; 125 | final int bottom = scrollRangeY; 126 | 127 | if (newScrollX > right) { 128 | newScrollX = right; 129 | } else if (newScrollX < left) { 130 | newScrollX = left; 131 | } 132 | 133 | if (newScrollY > bottom) { 134 | newScrollY = bottom; 135 | } else if (newScrollY < top) { 136 | newScrollY = top; 137 | } 138 | if (newScrollX < 0) { 139 | newScrollX = 0; 140 | } 141 | if (newScrollY < 0) { 142 | newScrollY = 0; 143 | } 144 | scrollTo(newScrollX, newScrollY); 145 | } 146 | 147 | ``` 148 | 149 | 滚动可以在 onScroll 回调拿到,distanceX、distanceY 分别是 X 轴和 Y 轴上拿到的 150 | 滚动距离,getScrollX()、getScrollY() 则拿到了当前的滚动距离,这样就可以算出 151 | newScrollX 和 newScrollY 了,最后调用 scrollTo 进行滚动 。还有一点要注意的是,scrollX 和 ScrollY 都有滚动范围,实现如下: 152 | 153 | 154 | ``` 155 | // mCurrentZoom 是当前的缩放值;ScrollRange 大于 0 的时候说明可以滚动 156 | 157 | private int getScrollRangeX() { 158 | final int contentWidth = getWidth() - getPaddingRight() - getPaddingLeft(); 159 | return (getContentWidth() - contentWidth); 160 | } 161 | 162 | private int getContentWidth() { 163 | return (int) (child().getWidth() * mCurrentZoom); 164 | } 165 | 166 | private int getScrollRangeY() { 167 | final int contentHeight = getHeight() - getPaddingBottom() - getPaddingTop(); 168 | return getContentHeight() - contentHeight; 169 | } 170 | 171 | private int getContentHeight() { 172 | return (int) (child().getHeight() * mCurrentZoom); 173 | } 174 | 175 | private View child() { 176 | return getChildAt(0); 177 | } 178 | 179 | ``` 180 | 181 | ### 2.4 实现 Fling(抛掷)滚动 182 | Fling 滚动就是我们往某个方向快速滑动,当我们手指抬起后,View 还会沿着某个方向继续滚动。 183 | 184 | 185 | ``` 186 | private GestureDetector.SimpleOnGestureListener mSimpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() { 187 | @Override 188 | public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 189 | if (!isEnabled()) { 190 | return false; 191 | } 192 | fling((int) -velocityX, (int) -velocityY); 193 | return true; 194 | } 195 | }; 196 | 197 | private boolean fling(int velocityX, int velocityY) { 198 | if (Math.abs(velocityX) < mMinimumVelocity) { 199 | velocityX = 0; 200 | } 201 | if (Math.abs(velocityY) < mMinimumVelocity) { 202 | velocityY = 0; 203 | } 204 | final int scrollY = getScrollY(); 205 | final int scrollX = getScrollX(); 206 | final boolean canFlingX = (scrollX > 0 || velocityX > 0) && 207 | (scrollX < getScrollRangeX() || velocityX < 0); 208 | final boolean canFlingY = (scrollY > 0 || velocityY > 0) && 209 | (scrollY < getScrollRangeY() || velocityY < 0); 210 | boolean canFling = canFlingY || canFlingX; 211 | if (canFling) { 212 | velocityX = Math.max(-mMaximumVelocity, Math.min(velocityX, mMaximumVelocity)); 213 | velocityY = Math.max(-mMaximumVelocity, Math.min(velocityY, mMaximumVelocity)); 214 | int height = getHeight() - getPaddingBottom() - getPaddingTop(); 215 | int width = getWidth() - getPaddingRight() - getPaddingLeft(); 216 | int bottom = getContentHeight(); 217 | int right = getContentWidth(); 218 | mOverScroller.fling(getScrollX(), getScrollY(), velocityX, velocityY, 0, Math.max(0, right - width), 0, 219 | Math.max(0, bottom - height), 0, 0); 220 | notifyInvalidate(); 221 | return true; 222 | } 223 | return false; 224 | } 225 | 226 | private void notifyInvalidate() { 227 | // 效果和 invalidate 一样,但是会使得动画更平滑 228 | ViewCompat.postInvalidateOnAnimation(this); 229 | } 230 | 231 | @Override 232 | public void computeScroll() { 233 | super.computeScroll(); 234 | if (mOverScroller.computeScrollOffset()) { // 判断是否可以滚动 235 | int oldX = getScrollX(); 236 | int oldY = getScrollY(); 237 | int x = mOverScroller.getCurrX(); 238 | int y = mOverScroller.getCurrY(); 239 | if (oldX != x || oldY != y) { 240 | final int rangeY = getScrollRangeY(); 241 | final int rangeX = getScrollRangeX(); 242 | processScroll(x - oldX, y - oldY, rangeX, rangeY); 243 | } 244 | if (!mOverScroller.isFinished()) { // 如果滚动没有停止,那就再调用一次 notifyInvalidate(),会触发下一次的 computeScroll() 245 | notifyInvalidate(); 246 | } 247 | } 248 | } 249 | ``` 250 | 251 | 大体的思路是通过 onFling() 拿到手势,然后计算是否能够滑动,可以的话就调用 252 | mOverScroller.fling() 开始滚动,最后不要忘了调用 notifyInvalidate()。调用 253 | notifyInvalidate() 后我们就可以在 computeScroll() 回调中使用 processScroll() 进行滚动 254 | 255 | 256 | ### 2.5 手势缩放 257 | 258 | 259 | ``` 260 | private ScaleGestureDetector.SimpleOnScaleGestureListener mSimpleOnScaleGestureListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() { 261 | @Override 262 | public boolean onScale(ScaleGestureDetector detector) { 263 | if (!isEnabled()) { 264 | return false; 265 | } 266 | float newScale; 267 | newScale = mCurrentZoom * detector.getScaleFactor(); 268 | if (newScale > mMaxZoom) { 269 | newScale = mMaxZoom; 270 | } else if (newScale < mMinZoom) { 271 | newScale = mMinZoom; 272 | } 273 | setScale(newScale, (int) detector.getFocusX(), (int) detector.getFocusY()); 274 | return true; 275 | } 276 | 277 | @Override 278 | public boolean onScaleBegin(ScaleGestureDetector detector) { 279 | return true; 280 | } 281 | 282 | @Override 283 | public void onScaleEnd(ScaleGestureDetector detector) { 284 | } 285 | }; 286 | 287 | public void setScale(float scale, int centerX, int centerY) { 288 | float preScale = mCurrentZoom; 289 | mCurrentZoom = scale; 290 | int sX = getScrollX(); 291 | int sY = getScrollY(); 292 | int dx = (int) ((sX + centerX) * (scale / preScale - 1)); 293 | int dy = (int) ((sY + centerY) * (scale / preScale - 1)); 294 | child().setPivotX(0); 295 | child().setPivotY(0); 296 | child().setScaleX(mCurrentZoom); 297 | child().setScaleY(mCurrentZoom); 298 | processScroll(dx, dy, getScrollRangeX(), getScrollRangeY()); 299 | notifyInvalidate(); 300 | } 301 | ``` 302 | 303 | 实现思路是 onScale() 中拿到缩放手势,缩放不仅会影响到 scale,其实还会影响到 304 | scrollX、scrollY,所以缩放的时候,也要调用 processScroll() 。由于我们的 scrollX、scrollY 是基于 ZoomLayout 的左上角计算的(这里先默认子 View 左上角和 `ZoomLayout` 左上角已知,后面还需要适配这一点),所以我们这里的缩放也要基于左上角计算,通过 setPivotX(0),setPivotY(0) 设置缩放中心点为左上角 305 | 306 | ### 2.6 双击缩放 307 | 308 | 309 | ``` 310 | private GestureDetector.SimpleOnGestureListener mSimpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() { 311 | @Override 312 | public boolean onDoubleTap(MotionEvent e) { 313 | float newScale; 314 | if (mCurrentZoom < 1) { 315 | newScale = 1; 316 | } else if (mCurrentZoom < mDoubleClickZoom) { 317 | newScale = mDoubleClickZoom; 318 | } else { 319 | newScale = 1; 320 | } 321 | smoothScale(newScale, (int) e.getX(), (int) e.getY()); 322 | return true; 323 | } 324 | }; 325 | 326 | public void smoothScale(float newScale, int centerX, int centerY) { 327 | if (mCurrentZoom > newScale) { 328 | if (mAccelerateInterpolator == null) { 329 | mAccelerateInterpolator = new AccelerateInterpolator(); 330 | } 331 | mScaleHelper.startScale(mCurrentZoom, newScale, centerX, centerY, mAccelerateInterpolator); 332 | } else { 333 | if (mDecelerateInterpolator == null) { 334 | mDecelerateInterpolator = new DecelerateInterpolator(); 335 | } 336 | mScaleHelper.startScale(mCurrentZoom, newScale, centerX, centerY, mDecelerateInterpolator); 337 | } 338 | notifyInvalidate(); 339 | } 340 | 341 | @Override 342 | public void computeScroll() { 343 | super.computeScroll(); 344 | if (mScaleHelper.computeScrollOffset()) { 345 | setScale(mScaleHelper.getCurScale(), mScaleHelper.getStartX(), mScaleHelper.getStartY()); 346 | } 347 | } 348 | 349 | ``` 350 | 351 | 双击缩放和手势缩放都是缩放,不同点在于双击缩放我们需要自己去计算每个时间点的 352 | scale,比如说双击后,`View` 会在 200 ms 内从 1倍 scale 变成 2倍 scale,那么我们就要自己去计算 200ms,scale 的变化。看到这里大家都应该想到了其实就是对 scale 这个值做一个属性动画嘛。这里将其封装在了 ScaleHelper 中。跟 Fling 的思路一样,通过 notifyInvalidate() 和 computeScroll() 实现循环。 353 | 354 | 355 | ## 3. 其他功能 356 | 357 | ### 3.1 适配 ViewPager 358 | 很简单,`ViewPager` 会通过子 `View` 的 `canScrollHorizontally` 和 `canScrollVertically` 判断是否可以横向、竖向滚动,`ZoomLayout` 重写他们就是了 359 | 360 | 361 | ``` 362 | @Override 363 | public boolean canScrollHorizontally(int direction) { 364 | if (direction > 0) { 365 | return getScrollX() < getScrollRangeX(); 366 | } else { 367 | return getScrollX() > 0 && getScrollRangeX() > 0; 368 | } 369 | } 370 | 371 | @Override 372 | public boolean canScrollVertically(int direction) { 373 | if (direction > 0) { 374 | return getScrollY() < getScrollRangeY(); 375 | } else { 376 | return getScrollY() > 0 && getScrollRangeY() > 0; 377 | } 378 | } 379 | ``` 380 | 381 | ### 3.2 事件传递 382 | 383 | 我们不希望 ZoomLayout 或者子 View 把事件消耗掉,而是两者都能收到事件。 384 | 下面是我的实现: 385 | `ZoomLayout` 在 `dispatchTouchEvent` 去接收事件,因为这样即使子 `View` 消耗了事件,事件依然会经过这里。 386 | 然后在 `onDraw` 设置 `child().setClickable(true)`,这里是为了让事件能被 387 | 子 View 消耗掉,因为只有子 View 消耗了事件,事件才能一直传递到 `ZoomLayout` 中去。 388 | ``` 389 | @Override 390 | public boolean dispatchTouchEvent(MotionEvent ev) { 391 | mGestureDetector.onTouchEvent(ev); 392 | mScaleDetector.onTouchEvent(ev); 393 | return super.dispatchTouchEvent(ev); 394 | } 395 | 396 | @Override 397 | protected void onDraw(Canvas canvas) { 398 | super.onDraw(canvas); 399 | child().setClickable(true); 400 | } 401 | ``` 402 | 403 | ### 3.3 布局的控制 404 | 405 | 我们希望 `ZoomLayout` 的宽高比子 View 的宽高大的时候,居中显示,否则就显示为 406 | `left|top`,我的思路是我们可以在 `onDraw` 中拿到准确的宽、高,通过宽高的对比,决定使用什么布局 407 | 408 | 409 | ``` 410 | @Override 411 | protected void onDraw(Canvas canvas) { 412 | super.onDraw(canvas); 413 | child().setClickable(true); 414 | if (child().getHeight() < getHeight() || child().getWidth() < getWidth()) { 415 | setGravity(Gravity.CENTER); 416 | } else { 417 | setGravity(Gravity.TOP); 418 | } 419 | } 420 | ``` 421 | 422 | 当适配到这里的时候,我们会发现一个问题,比如子 View 的高度小于 `ZoomLayout` 的时候,我们是安装子 View 的中心放大,如果这是我们放大子 View,放大到子 View 高度大于 `ZoomLayout`,我们这时候需要将子 `View` translate 到 `ZoomLayout` 的顶部,原因是我们第 2.5 步说到的 scroolX、scrollY 是基于左上角计算的。所以适配后的代码是这样的 423 | 424 | 425 | ``` 426 | public void setScale(float scale, int centerX, int centerY) { 427 | float preScale = mCurrentZoom; 428 | mCurrentZoom = scale; 429 | int sX = getScrollX(); 430 | int sY = getScrollY(); 431 | int dx = (int) ((sX + centerX) * (scale / preScale - 1)); 432 | int dy = (int) ((sY + centerY) * (scale / preScale - 1)); 433 | if (getScrollRangeX() < 0) { 434 | child().setPivotX(child().getWidth() / 2); 435 | child().setTranslationX(0); 436 | } else { 437 | child().setPivotX(0); 438 | int willTranslateX = -(child().getLeft()); 439 | child().setTranslationX(willTranslateX); 440 | } 441 | if (getScrollRangeY() < 0) { 442 | child().setPivotY(child().getHeight() / 2); 443 | child().setTranslationY(0); 444 | } else { 445 | int willTranslateY = -(child().getTop()); 446 | child().setTranslationY(willTranslateY); 447 | child().setPivotY(0); 448 | } 449 | child().setScaleX(mCurrentZoom); 450 | child().setScaleY(mCurrentZoom); 451 | processScroll(dx, dy, getScrollRangeX(), getScrollRangeY()); 452 | notifyInvalidate(); 453 | } 454 | ``` 455 | 456 | 在适配业务的过程,遇到了另外一个问题,就是 ZoomLayout 的高度有可能是会发生变化的,比如键盘弹出来的时候,ZoomLayout 可能会被压小, 457 | 我的思路是在 `onDraw` 中监听宽高的变化,有变化的时候,调用 `setScale` 去设置为正确的状态。 458 | 459 | 460 | ``` 461 | public void setScale(float scale, int centerX, int centerY) { 462 | // 记下最近一次的状态 463 | mLastCenterX = centerX; 464 | mLastCenterY = centerY; 465 | mCurrentZoom = scale; 466 | } 467 | 468 | 469 | @Override 470 | protected void onLayout(boolean changed, int l, int t, int r, int b) { 471 | super.onLayout(changed, l, t, r, b); 472 | if (mNeedReScale) { 473 | // 需要重新刷新,因为宽高已经发生变化 474 | setScale(mCurrentZoom, mLastCenterX, mLastCenterY); 475 | mNeedReScale = false; 476 | } 477 | } 478 | 479 | @Override 480 | protected void onDraw(Canvas canvas) { 481 | super.onDraw(canvas); 482 | if (mLastChildWidth != child().getWidth() || mLastChildHeight != child().getHeight() || mLastWidth != getWidth() 483 | || mLastHeight != getHeight()) { 484 | // 宽高变化后,记录需要重新刷新,放在下次 onLayout 处理,避免 View 的一些配置:比如 getTop() 没有初始化好 485 | // 下次放在 onLayout 处理的原因是 setGravity 会在 onLayout 确定完位置,这时候去 setScale 导致位置的变化就不会导致用户看到 486 | // 闪一下的问题 487 | mNeedReScale = true; 488 | } 489 | mLastChildWidth = child().getWidth(); 490 | mLastChildHeight = child().getHeight(); 491 | mLastWidth = child().getWidth(); 492 | mLastHeight = getHeight(); 493 | if (mNeedReScale) { 494 | notifyInvalidate(); 495 | } 496 | } 497 | ``` 498 | 499 | 上面有个小细节是发现 mNeedReScale 为 true 时没有立即调用 `setScale`,因为这时候 `setGravity` 还没有生效,我把它放在了下一次 500 | `onLayout` 中 501 | 502 | 503 | ## 总结 504 | 505 | 实现一个 ZoomLayout 主要是需要熟悉手势的使用,然后实现过程中比较难也比较麻烦的是各种坐标相关的计算,以及各种细节的适配。实现过程中很多代码都参考了 [LargeImageView](https://github.com/LuckyJayce/LargeImage) 、`ScrollView`。 506 | `ZoomLayout` 的实现还有很多改进的地方,比如事件的处理等,欢迎交流~ 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## ZoomLayout 2 | 3 | Android 视图缩放组件 4 | 5 | 实现的功能点 6 | 7 | 1. 触摸滑动及惯性滑动 8 | 2. 多指缩放 9 | 3. 双击缩放 10 | 11 | 同时处理了以下细节 12 | 1. 滑动冲突,比如将 `ZoomLayout` 放在 `ViewPager` 中 13 | 2. 事件冲突,`ZoomLayout` 和 子 `View` 都能接收事件 14 | 3. `ZoomLayout` 宽、高更新时能够自适应布局 15 | 16 | 17 | ## 效果 18 | ![zoomlayout.gif](https://github.com/guangmomo/ZoomLayout/blob/master/demofile/zoomLayout.gif) 19 | 20 | Download Demo [Apk](https://github.com/guangmomo/ZoomLayout/blob/master/demofile/zoomLayout.apk) 21 | 22 | ## 使用 23 | 24 | ``` 25 | compile 'com.xlw.zoom:zoomlayout:1.0.0' 26 | ``` 27 | 28 | 29 | ``` 30 | 31 | 39 | 40 | 44 | 45 | 51 | 52 | 58 | 59 | 60 | 61 | 62 | ``` 63 | 64 | 支持的属性 65 | 66 | 67 | 属性 | 意义 68 | ---|--- 69 | max_zoom | 最大缩放倍数 70 | min_zoom | 最小缩放倍数 71 | double_click_zoom | 双击缩放倍数 72 | 73 | ## 实现原理 74 | 75 | [简书链接](https://www.jianshu.com/p/f0710c28f061) 76 | 77 | [github 链接](https://github.com/guangmomo/ZoomLayout/blob/master/PRINCIPLE.md/) -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 28 5 | defaultConfig { 6 | applicationId "com.xuliwen.zoom.demo" 7 | minSdkVersion 21 8 | targetSdkVersion 28 9 | versionCode 1 10 | versionName "1.0" 11 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 12 | } 13 | signingConfigs { 14 | pro { 15 | storeFile file('myapp.keystore') 16 | storePassword '123456' 17 | keyAlias 'myapp' 18 | keyPassword '123456' 19 | } 20 | } 21 | buildTypes { 22 | release { 23 | minifyEnabled false 24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 25 | } 26 | } 27 | } 28 | 29 | dependencies { 30 | implementation fileTree(dir: 'libs', include: ['*.jar']) 31 | implementation 'androidx.appcompat:appcompat:1.0.2' 32 | implementation project(':library') 33 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 34 | testImplementation 'junit:junit:4.12' 35 | androidTestImplementation 'androidx.test:runner:1.1.1' 36 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' 37 | } 38 | -------------------------------------------------------------------------------- /app/myapp.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/myapp.keystore -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/release/output.json: -------------------------------------------------------------------------------- 1 | [{"outputType":{"type":"APK"},"apkData":{"type":"MAIN","splits":[],"versionCode":1,"versionName":"1.0","enabled":true,"outputFile":"app-release.apk","fullName":"release","baseName":"release"},"path":"app-release.apk","properties":{}}] -------------------------------------------------------------------------------- /app/src/androidTest/java/com/xuliwen/zoom/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom; 2 | 3 | import android.content.Context; 4 | 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | 8 | import androidx.test.platform.app.InstrumentationRegistry; 9 | import androidx.test.runner.AndroidJUnit4; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | 25 | assertEquals("com.xuliwen.zoomlayout", appContext.getPackageName()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /app/src/main/java/com/xuliwen/zoom/demo/LongPictureActivity.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom.demo; 2 | 3 | import androidx.appcompat.app.AppCompatActivity; 4 | 5 | import android.os.Bundle; 6 | 7 | 8 | public class LongPictureActivity extends AppCompatActivity { 9 | 10 | @Override 11 | protected void onCreate(Bundle savedInstanceState) { 12 | super.onCreate(savedInstanceState); 13 | setContentView(R.layout.layout_long_picture); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/xuliwen/zoom/demo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom.demo; 2 | 3 | import androidx.appcompat.app.AppCompatActivity; 4 | 5 | import android.content.Intent; 6 | import android.os.Bundle; 7 | import android.view.View; 8 | 9 | 10 | public class MainActivity extends AppCompatActivity { 11 | 12 | 13 | @Override 14 | protected void onCreate(Bundle savedInstanceState) { 15 | super.onCreate(savedInstanceState); 16 | setContentView(R.layout.activity_main); 17 | 18 | findViewById(R.id.zoom_demo_to_long_picture_activity).setOnClickListener(new View.OnClickListener() { 19 | @Override 20 | public void onClick(View v) { 21 | startActivity(new Intent(MainActivity.this, LongPictureActivity.class)); 22 | } 23 | }); 24 | 25 | findViewById(R.id.zoom_demo_to_short_picture_activity).setOnClickListener(new View.OnClickListener() { 26 | @Override 27 | public void onClick(View v) { 28 | startActivity(new Intent(MainActivity.this, ShortPictureActivity.class)); 29 | } 30 | }); 31 | 32 | findViewById(R.id.zoom_demo_to_viewpager_activity).setOnClickListener(new View.OnClickListener() { 33 | @Override 34 | public void onClick(View v) { 35 | startActivity(new Intent(MainActivity.this, ViewPagerActivity.class)); 36 | } 37 | }); 38 | 39 | findViewById(R.id.zoom_demo_to_size_change_activity).setOnClickListener(new View.OnClickListener() { 40 | @Override 41 | public void onClick(View v) { 42 | startActivity(new Intent(MainActivity.this, SizeChangeActivity.class)); 43 | } 44 | }); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/com/xuliwen/zoom/demo/MyPagerAdapter.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom.demo; 2 | 3 | import android.view.View; 4 | import android.view.ViewGroup; 5 | 6 | 7 | import androidx.annotation.NonNull; 8 | import androidx.viewpager.widget.PagerAdapter; 9 | 10 | public class MyPagerAdapter extends PagerAdapter { 11 | 12 | 13 | @Override 14 | public int getCount() { 15 | return 3; 16 | } 17 | 18 | @NonNull 19 | @Override 20 | public Object instantiateItem(@NonNull ViewGroup container, int position) { 21 | View view; 22 | if (position == 0) { 23 | view = View.inflate(container.getContext(), R.layout.layout_long_picture, null); 24 | } else if (position == 1) { 25 | view = View.inflate(container.getContext(), R.layout.layout_short_picture, null); 26 | } else { 27 | view = View.inflate(container.getContext(), R.layout.layout_other_picture, null); 28 | } 29 | container.addView(view); 30 | return view; 31 | } 32 | 33 | @Override 34 | public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { 35 | container.removeView((View) object); 36 | } 37 | 38 | @Override 39 | public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { 40 | return view == object; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /app/src/main/java/com/xuliwen/zoom/demo/ShortPictureActivity.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom.demo; 2 | 3 | import androidx.appcompat.app.AppCompatActivity; 4 | 5 | import android.os.Bundle; 6 | 7 | 8 | public class ShortPictureActivity extends AppCompatActivity { 9 | 10 | @Override 11 | protected void onCreate(Bundle savedInstanceState) { 12 | super.onCreate(savedInstanceState); 13 | setContentView(R.layout.layout_short_picture); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/xuliwen/zoom/demo/SizeChangeActivity.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom.demo; 2 | 3 | import androidx.appcompat.app.AppCompatActivity; 4 | 5 | import android.os.Bundle; 6 | 7 | 8 | public class SizeChangeActivity extends AppCompatActivity { 9 | 10 | @Override 11 | protected void onCreate(Bundle savedInstanceState) { 12 | super.onCreate(savedInstanceState); 13 | setContentView(R.layout.activity_size_change); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/xuliwen/zoom/demo/ViewPagerActivity.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom.demo; 2 | 3 | import androidx.appcompat.app.AppCompatActivity; 4 | import androidx.viewpager.widget.ViewPager; 5 | 6 | import android.os.Bundle; 7 | 8 | 9 | public class ViewPagerActivity extends AppCompatActivity { 10 | 11 | @Override 12 | protected void onCreate(Bundle savedInstanceState) { 13 | super.onCreate(savedInstanceState); 14 | setContentView(R.layout.activity_view_pager); 15 | ViewPager viewPager = findViewById(R.id.viewPager); 16 | viewPager.setOffscreenPageLimit(2); 17 | MyPagerAdapter myPagerAdapter = new MyPagerAdapter(); 18 | viewPager.setAdapter(myPagerAdapter); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 20 | 21 | 32 | 33 | 44 | 45 | 56 | 57 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_size_change.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 15 | 16 | 22 | 23 | 24 | 25 | 28 | 29 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_view_pager.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/layout/layout_long_picture.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 15 | 16 | 22 | 23 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/layout/layout_other_picture.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 16 | 17 | -------------------------------------------------------------------------------- /app/src/main/res/layout/layout_short_picture.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 16 | 17 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/image1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xhdpi/image1.jpg -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/image2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xhdpi/image2.jpg -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/other.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xhdpi/other.jpeg -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/short_pic.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xhdpi/short_pic.jpeg -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/size_change.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xhdpi/size_change.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ZoomLayout 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/xuliwen/zoom/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | google() 6 | jcenter() 7 | 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.5.0' 11 | classpath 'com.novoda:bintray-release:0.9.1' 12 | 13 | // NOTE: Do not place your application dependencies here; they belong 14 | // in the individual module build.gradle files 15 | } 16 | } 17 | 18 | allprojects { 19 | repositories { 20 | google() 21 | jcenter() 22 | 23 | } 24 | } 25 | 26 | task clean(type: Delete) { 27 | delete rootProject.buildDir 28 | } 29 | -------------------------------------------------------------------------------- /demofile/zoomLayout.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/demofile/zoomLayout.apk -------------------------------------------------------------------------------- /demofile/zoomLayout.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/demofile/zoomLayout.gif -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | android.enableR8=false 21 | android.enableD8=false 22 | 23 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Oct 16 20:46:58 CST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.novoda.bintray-release' 3 | 4 | 5 | android { 6 | compileSdkVersion 28 7 | 8 | 9 | defaultConfig { 10 | minSdkVersion 21 11 | targetSdkVersion 28 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 16 | consumerProguardFiles 'consumer-rules.pro' 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | 26 | } 27 | 28 | dependencies { 29 | implementation fileTree(dir: 'libs', include: ['*.jar']) 30 | 31 | implementation 'androidx.appcompat:appcompat:1.0.2' 32 | testImplementation 'junit:junit:4.12' 33 | androidTestImplementation 'androidx.test:runner:1.1.1' 34 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' 35 | } 36 | 37 | //生成源文件 38 | task sourcesJar(type: Jar) { 39 | from android.sourceSets.main.java.srcDirs 40 | classifier = 'sources' 41 | } 42 | 43 | //生成Javadoc文档 44 | task javadoc(type: Javadoc) { 45 | source = android.sourceSets.main.java.srcDirs 46 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 47 | } 48 | 49 | //文档打包成jar 50 | task javadocJar(type: Jar, dependsOn: javadoc) { 51 | classifier = 'javadoc' 52 | from javadoc.destinationDir 53 | } 54 | 55 | //拷贝javadoc文件 56 | task copyDoc(type: Copy) { 57 | from "${buildDir}/docs/" 58 | into "docs" 59 | } 60 | 61 | //上传到JCenter所需要的源码文件 62 | artifacts { 63 | archives javadocJar 64 | archives sourcesJar 65 | } 66 | 67 | //解决 JavaDoc 中文注释生成失败的问题 68 | tasks.withType(Javadoc) { 69 | options.addStringOption('Xdoclint:none', '-quiet') 70 | options.addStringOption('encoding', 'UTF-8') 71 | options.addStringOption('charSet', 'UTF-8') 72 | } 73 | 74 | 75 | //发布到 Bintray 76 | publish { 77 | userOrg = 'xueleven' //bintray.com 注册的用户名 78 | groupId = 'com.xlw.zoom' //以后访问 jcenter上此项目的路径,一般和库项目的包名一致 79 | artifactId = 'zoomlayout' //bintray.com 创建的 Package 名 80 | publishVersion = '1.0.0' //版本号 81 | desc = '1.0.0' //版本说明,随意 82 | website = 'https://github.com/guangmomo/ZoomLayout' //关于这个开源项目的网站,随意 83 | } -------------------------------------------------------------------------------- /library/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guangmomo/ZoomLayout/2b2e34f96f4ca267b14ec692166d93bda8c1086b/library/consumer-rules.pro -------------------------------------------------------------------------------- /library/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /library/src/androidTest/java/com/xuliwen/zoom/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom; 2 | 3 | import android.content.Context; 4 | 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | 8 | import androidx.test.platform.app.InstrumentationRegistry; 9 | import androidx.test.runner.AndroidJUnit4; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | 25 | assertEquals("com.xuliwen.zoom.test", appContext.getPackageName()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /library/src/main/java/com/xuliwen/zoom/ScaleHelper.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom; 2 | 3 | import android.view.animation.AnimationUtils; 4 | import android.view.animation.Interpolator; 5 | 6 | /** 7 | * Created by xuliwen on 2019/10/12. 8 | */ 9 | 10 | public class ScaleHelper { 11 | 12 | private long mStartTime; 13 | private Interpolator mInterpolator; 14 | private float mScale; 15 | private float mToScale; 16 | private int mStartX; 17 | private int mDuration; 18 | private boolean mFinished = true; 19 | private int mStartY; 20 | 21 | public void startScale(float scale, float toScale, int x, int y, Interpolator interpolator) { 22 | mStartTime = AnimationUtils.currentAnimationTimeMillis(); 23 | mInterpolator = interpolator; 24 | mScale = scale; 25 | mToScale = toScale; 26 | mStartX = x; 27 | mStartY = y; 28 | float d; 29 | if (toScale > scale) { 30 | d = toScale / scale; 31 | } else { 32 | d = scale / toScale; 33 | } 34 | if (d > 4) { 35 | d = 4; 36 | } 37 | //倍数差值越大 执行时间越久 280 - 340 38 | mDuration = (int) (220 + Math.sqrt(d * 3600)); 39 | mFinished = false; 40 | } 41 | 42 | /** 43 | * Call this when you want to know the new location. If it returns true, the 44 | * animation is not yet finished. 45 | */ 46 | public boolean computeScrollOffset() { 47 | if (isFinished()) { 48 | return false; 49 | } 50 | long time = AnimationUtils.currentAnimationTimeMillis(); 51 | // Any scroller can be used for time, since they were started 52 | // together in scroll mode. We use X here. 53 | final long elapsedTime = time - mStartTime; 54 | 55 | final int duration = mDuration; 56 | if (elapsedTime < duration) { 57 | final float q = mInterpolator.getInterpolation(elapsedTime / (float) duration); 58 | mScale = mScale + q * (mToScale - mScale); 59 | } else { 60 | mScale = mToScale; 61 | mFinished = true; 62 | } 63 | return true; 64 | } 65 | 66 | private boolean isFinished() { 67 | return mFinished; 68 | } 69 | 70 | public float getCurScale() { 71 | return mScale; 72 | } 73 | 74 | public int getStartX() { 75 | return mStartX; 76 | } 77 | 78 | public int getStartY() { 79 | return mStartY; 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /library/src/main/java/com/xuliwen/zoom/ZoomLayout.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.graphics.Canvas; 6 | import android.util.AttributeSet; 7 | import android.util.Log; 8 | import android.view.GestureDetector; 9 | import android.view.Gravity; 10 | import android.view.MotionEvent; 11 | import android.view.ScaleGestureDetector; 12 | import android.view.View; 13 | import android.view.ViewConfiguration; 14 | import android.view.animation.AccelerateInterpolator; 15 | import android.view.animation.DecelerateInterpolator; 16 | import android.widget.LinearLayout; 17 | import android.widget.OverScroller; 18 | 19 | import com.xuliwen.zoom.library.R; 20 | 21 | import androidx.annotation.Nullable; 22 | import androidx.core.view.ViewCompat; 23 | 24 | import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; 25 | 26 | /** 27 | * Created by xuliwen on 2019/10/12 28 | * 29 | * 简介:与业务无关的缩放 ViewGroup,只能有一个直接子 View 30 | * 31 | * 实现过程:结合自身业务需要,参考了 LargeImageView、ScrollView 来实现 32 | * 33 | * 作用: 34 | * 1、单指、多指滑动及惯性滑动 35 | * 2、双击缩放 36 | * 3、多指缩放 37 | * 38 | * 注意点: 39 | * 1、如果子 View 宽、高小于 ZoomLayout,会将子 View 在宽、高方向上居中 40 | * 41 | */ 42 | public class ZoomLayout extends LinearLayout { 43 | 44 | 45 | private static final String TAG = "ZoomLayout"; 46 | private static final float DEFAULT_MIN_ZOOM = 1.0f; 47 | private static final float DEFAULT_MAX_ZOOM = 4.0f; 48 | private static final float DEFAULT_DOUBLE_CLICK_ZOOM = 2.0f; 49 | 50 | private float mDoubleClickZoom; 51 | private float mMinZoom; 52 | private float mMaxZoom; 53 | private float mCurrentZoom = 1; 54 | private int mMinimumVelocity; 55 | private int mMaximumVelocity; 56 | private boolean mScrollBegin; // 是否已经开始滑动 57 | 58 | private ScaleGestureDetector mScaleDetector; 59 | private GestureDetector mGestureDetector; 60 | private OverScroller mOverScroller; 61 | private ScaleHelper mScaleHelper; 62 | private AccelerateInterpolator mAccelerateInterpolator; 63 | private DecelerateInterpolator mDecelerateInterpolator; 64 | private ZoomLayoutGestureListener mZoomLayoutGestureListener; 65 | private int mLastChildHeight; 66 | private int mLastChildWidth; 67 | private int mLastHeight; 68 | private int mLastWidth; 69 | private int mLastCenterX; 70 | private int mLastCenterY; 71 | private boolean mNeedReScale; 72 | 73 | public ZoomLayout(Context context) { 74 | super(context); 75 | init(context, null); 76 | } 77 | 78 | public ZoomLayout(Context context, AttributeSet attrs) { 79 | super(context, attrs); 80 | init(context, attrs); 81 | } 82 | 83 | public ZoomLayout(Context context, AttributeSet attrs, int defStyle) { 84 | super(context, attrs, defStyle); 85 | init(context, attrs); 86 | } 87 | 88 | 89 | private void init(Context context, @Nullable AttributeSet attrs) { 90 | mScaleDetector = new ScaleGestureDetector(context, mSimpleOnScaleGestureListener); 91 | mGestureDetector = new GestureDetector(context, mSimpleOnGestureListener); 92 | mOverScroller = new OverScroller(getContext()); 93 | mScaleHelper = new ScaleHelper(); 94 | final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 95 | mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); 96 | mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 97 | setWillNotDraw(false); 98 | if (attrs != null) { 99 | TypedArray array = null; 100 | try { 101 | array = context.obtainStyledAttributes(attrs, R.styleable.ZoomLayout); 102 | mMinZoom = array.getFloat(R.styleable.ZoomLayout_min_zoom, DEFAULT_MIN_ZOOM); 103 | mMaxZoom = array.getFloat(R.styleable.ZoomLayout_max_zoom, DEFAULT_MAX_ZOOM); 104 | mDoubleClickZoom = array.getFloat(R.styleable.ZoomLayout_double_click_zoom, DEFAULT_DOUBLE_CLICK_ZOOM); 105 | if (mDoubleClickZoom > mMaxZoom) { 106 | mDoubleClickZoom = mMaxZoom; 107 | } 108 | } catch (Exception e) { 109 | Log.e(TAG, TAG, e); 110 | } finally { 111 | if (array != null) { 112 | array.recycle(); 113 | } 114 | } 115 | } 116 | } 117 | 118 | private ScaleGestureDetector.SimpleOnScaleGestureListener mSimpleOnScaleGestureListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() { 119 | @Override 120 | public boolean onScale(ScaleGestureDetector detector) { 121 | if (!isEnabled()) { 122 | return false; 123 | } 124 | float newScale; 125 | newScale = mCurrentZoom * detector.getScaleFactor(); 126 | if (newScale > mMaxZoom) { 127 | newScale = mMaxZoom; 128 | } else if (newScale < mMinZoom) { 129 | newScale = mMinZoom; 130 | } 131 | setScale(newScale, (int) detector.getFocusX(), (int) detector.getFocusY()); 132 | return true; 133 | } 134 | 135 | @Override 136 | public boolean onScaleBegin(ScaleGestureDetector detector) { 137 | if (mZoomLayoutGestureListener != null) { 138 | mZoomLayoutGestureListener.onScaleGestureBegin(); 139 | } 140 | return true; 141 | } 142 | 143 | @Override 144 | public void onScaleEnd(ScaleGestureDetector detector) { 145 | } 146 | }; 147 | 148 | private GestureDetector.SimpleOnGestureListener mSimpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() { 149 | 150 | 151 | @Override 152 | public boolean onDown(MotionEvent e) { 153 | if (!mOverScroller.isFinished()) { 154 | mOverScroller.abortAnimation(); 155 | } 156 | return true; 157 | } 158 | 159 | @Override 160 | public boolean onDoubleTap(MotionEvent e) { 161 | float newScale; 162 | if (mCurrentZoom < 1) { 163 | newScale = 1; 164 | } else if (mCurrentZoom < mDoubleClickZoom) { 165 | newScale = mDoubleClickZoom; 166 | } else { 167 | newScale = 1; 168 | } 169 | smoothScale(newScale, (int) e.getX(), (int) e.getY()); 170 | if (mZoomLayoutGestureListener != null) { 171 | mZoomLayoutGestureListener.onDoubleTap(); 172 | } 173 | return true; 174 | } 175 | 176 | @Override 177 | public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 178 | if (!isEnabled()) { 179 | return false; 180 | } 181 | if (!mScrollBegin) { 182 | mScrollBegin = true; 183 | if (mZoomLayoutGestureListener != null) { 184 | mZoomLayoutGestureListener.onScrollBegin(); 185 | } 186 | } 187 | processScroll((int) distanceX, (int) distanceY, getScrollRangeX(), getScrollRangeY()); 188 | return true; 189 | } 190 | 191 | /** 192 | * 193 | * @param velocityX 滑动的速度 = 滑动的距离(滑动的起点 - 滑动的终点) / 滑动的时长,所以向上滑是负的,向下滑是正的 194 | * @param velocityY 同上 195 | * @return 196 | */ 197 | @Override 198 | public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 199 | if (!isEnabled()) { 200 | return false; 201 | } 202 | fling((int) -velocityX, (int) -velocityY); 203 | return true; 204 | } 205 | }; 206 | 207 | 208 | private boolean fling(int velocityX, int velocityY) { 209 | if (Math.abs(velocityX) < mMinimumVelocity) { 210 | velocityX = 0; 211 | } 212 | if (Math.abs(velocityY) < mMinimumVelocity) { 213 | velocityY = 0; 214 | } 215 | final int scrollY = getScrollY(); 216 | final int scrollX = getScrollX(); 217 | // 只有在能够滚动的时候,才需要处理 Fling 218 | final boolean canFlingX = scrollX > 0 && scrollX < getScrollRangeX(); 219 | final boolean canFlingY = scrollY > 0 && scrollY < getScrollRangeY(); 220 | boolean canFling = canFlingY || canFlingX; 221 | if (canFling) { 222 | // 下面两行代码的作用是将 Fling 速度限制在 [-mMaximumVelocity, mMaximumVelocity] 之间 223 | velocityX = Math.max(-mMaximumVelocity, Math.min(velocityX, mMaximumVelocity)); 224 | velocityY = Math.max(-mMaximumVelocity, Math.min(velocityY, mMaximumVelocity)); 225 | int height = getHeight() - getPaddingBottom() - getPaddingTop(); 226 | int width = getWidth() - getPaddingRight() - getPaddingLeft(); 227 | int bottom = getContentHeight(); 228 | int right = getContentWidth(); 229 | // getScrollX(), getScrollY() 是 fling 开始的位置 230 | // velocityX, velocityY 滚动速度 231 | // 0, Math.max(0, right - width), 0, Math.max(0, bottom - height)。是滚动的范围 232 | // 0, 0 是可以往外滚动的距离,这里不支持往外滚动,直接传 0 233 | mOverScroller.fling(getScrollX(), getScrollY(), velocityX, velocityY, 0, Math.max(0, right - width), 0, 234 | Math.max(0, bottom - height), 0, 0); 235 | notifyInvalidate(); 236 | return true; 237 | } 238 | return false; 239 | } 240 | 241 | public void smoothScale(float newScale, int centerX, int centerY) { 242 | if (mCurrentZoom > newScale) { 243 | if (mAccelerateInterpolator == null) { 244 | mAccelerateInterpolator = new AccelerateInterpolator(); 245 | } 246 | mScaleHelper.startScale(mCurrentZoom, newScale, centerX, centerY, mAccelerateInterpolator); 247 | } else { 248 | if (mDecelerateInterpolator == null) { 249 | mDecelerateInterpolator = new DecelerateInterpolator(); 250 | } 251 | mScaleHelper.startScale(mCurrentZoom, newScale, centerX, centerY, mDecelerateInterpolator); 252 | } 253 | notifyInvalidate(); 254 | } 255 | 256 | private void notifyInvalidate() { 257 | // 效果和 invalidate 一样,但是会使得动画更平滑 258 | ViewCompat.postInvalidateOnAnimation(this); 259 | } 260 | 261 | 262 | public void setScale(float scale, int centerX, int centerY) { 263 | mLastCenterX = centerX; 264 | mLastCenterY = centerY; 265 | float preScale = mCurrentZoom; 266 | mCurrentZoom = scale; 267 | int sX = getScrollX(); 268 | int sY = getScrollY(); 269 | int dx = (int) ((sX + centerX) * (scale / preScale - 1)); 270 | int dy = (int) ((sY + centerY) * (scale / preScale - 1)); 271 | if (getScrollRangeX() < 0) { 272 | child().setPivotX(child().getWidth() / 2); 273 | child().setTranslationX(0); 274 | } else { 275 | child().setPivotX(0); 276 | int willTranslateX = -(child().getLeft()); 277 | child().setTranslationX(willTranslateX); 278 | } 279 | if (getScrollRangeY() < 0) { 280 | child().setPivotY(child().getHeight() / 2); 281 | child().setTranslationY(0); 282 | } else { 283 | int willTranslateY = -(child().getTop()); 284 | child().setTranslationY(willTranslateY); 285 | child().setPivotY(0); 286 | } 287 | child().setScaleX(mCurrentZoom); 288 | child().setScaleY(mCurrentZoom); 289 | processScroll(dx, dy, getScrollRangeX(), getScrollRangeY()); 290 | notifyInvalidate(); 291 | } 292 | 293 | 294 | private void processScroll(int deltaX, int deltaY, 295 | int scrollRangeX, int scrollRangeY) { 296 | int oldScrollX = getScrollX(); 297 | int oldScrollY = getScrollY(); 298 | int newScrollX = oldScrollX + deltaX; 299 | int newScrollY = oldScrollY + deltaY; 300 | final int left = 0; 301 | final int right = scrollRangeX; 302 | final int top = 0; 303 | final int bottom = scrollRangeY; 304 | 305 | if (newScrollX > right) { 306 | newScrollX = right; 307 | } else if (newScrollX < left) { 308 | newScrollX = left; 309 | } 310 | 311 | if (newScrollY > bottom) { 312 | newScrollY = bottom; 313 | } else if (newScrollY < top) { 314 | newScrollY = top; 315 | } 316 | if (newScrollX < 0) { 317 | newScrollX = 0; 318 | } 319 | if (newScrollY < 0) { 320 | newScrollY = 0; 321 | } 322 | Log.e(TAG, "newScrollX = " + newScrollX + " ,newScrollY = " + newScrollY); 323 | scrollTo(newScrollX, newScrollY); 324 | } 325 | 326 | 327 | private int getScrollRangeX() { 328 | final int contentWidth = getWidth() - getPaddingRight() - getPaddingLeft(); 329 | return (getContentWidth() - contentWidth); 330 | } 331 | 332 | private int getContentWidth() { 333 | return (int) (child().getWidth() * mCurrentZoom); 334 | } 335 | 336 | private int getScrollRangeY() { 337 | final int contentHeight = getHeight() - getPaddingBottom() - getPaddingTop(); 338 | return getContentHeight() - contentHeight; 339 | } 340 | 341 | private int getContentHeight() { 342 | return (int) (child().getHeight() * mCurrentZoom); 343 | } 344 | 345 | private View child() { 346 | return getChildAt(0); 347 | } 348 | 349 | @Override 350 | protected void onLayout(boolean changed, int l, int t, int r, int b) { 351 | super.onLayout(changed, l, t, r, b); 352 | if (mNeedReScale) { 353 | // 需要重新刷新,因为宽高已经发生变化 354 | setScale(mCurrentZoom, mLastCenterX, mLastCenterY); 355 | mNeedReScale = false; 356 | } 357 | } 358 | 359 | @Override 360 | protected void onDraw(Canvas canvas) { 361 | super.onDraw(canvas); 362 | child().setClickable(true); 363 | if (child().getHeight() < getHeight() || child().getWidth() < getWidth()) { 364 | setGravity(Gravity.CENTER); 365 | } else { 366 | setGravity(Gravity.TOP); 367 | } 368 | if (mLastChildWidth != child().getWidth() || mLastChildHeight != child().getHeight() || mLastWidth != getWidth() 369 | || mLastHeight != getHeight()) { 370 | // 宽高变化后,记录需要重新刷新,放在下次 onLayout 处理,避免 View 的一些配置:比如 getTop() 没有初始化好 371 | // 下次放在 onLayout 处理的原因是 setGravity 会在 onLayout 确定完位置,这时候去 setScale 导致位置的变化就不会导致用户看到 372 | // 闪一下的问题 373 | mNeedReScale = true; 374 | } 375 | mLastChildWidth = child().getWidth(); 376 | mLastChildHeight = child().getHeight(); 377 | mLastWidth = child().getWidth(); 378 | mLastHeight = getHeight(); 379 | if (mNeedReScale) { 380 | notifyInvalidate(); 381 | } 382 | } 383 | 384 | /** 385 | * 通常配合 Scroller、OverScroller 实现平滑滚动。如 Fling 的时候进行平滑滚动。 386 | * Scroller、OverScroller 负责计算一段时间内的 ScrollX、ScrollY 的平滑变化 387 | * 然后调用 ViewCompat.postInvalidateOnAnimation(this); 之后就可以在 388 | * computeScroll() 不断去获取 ScrollX、ScrollY 的变化了,再通过 ScrollTo 设置给 View 389 | */ 390 | @Override 391 | public void computeScroll() { 392 | super.computeScroll(); 393 | if (mScaleHelper.computeScrollOffset()) { 394 | setScale(mScaleHelper.getCurScale(), mScaleHelper.getStartX(), mScaleHelper.getStartY()); 395 | } 396 | if (mOverScroller.computeScrollOffset()) { 397 | int oldX = getScrollX(); 398 | int oldY = getScrollY(); 399 | int x = mOverScroller.getCurrX(); 400 | int y = mOverScroller.getCurrY(); 401 | if (oldX != x || oldY != y) { 402 | final int rangeY = getScrollRangeY(); 403 | final int rangeX = getScrollRangeX(); 404 | processScroll(x - oldX, y - oldY, rangeX, rangeY); 405 | } 406 | if (!mOverScroller.isFinished()) { 407 | notifyInvalidate(); 408 | } 409 | } 410 | } 411 | 412 | 413 | @Override 414 | public boolean dispatchTouchEvent(MotionEvent ev) { 415 | if (ev.getAction() == MotionEvent.ACTION_UP) { 416 | // 最后一根手指抬起的时候,重置 mScrollBegin 为 false 417 | mScrollBegin = false; 418 | } 419 | mGestureDetector.onTouchEvent(ev); 420 | mScaleDetector.onTouchEvent(ev); 421 | return super.dispatchTouchEvent(ev); 422 | } 423 | 424 | 425 | 426 | 427 | @Override 428 | protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, 429 | int parentHeightMeasureSpec, int heightUsed) { 430 | final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 431 | 432 | final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 433 | getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin 434 | + widthUsed, lp.width); 435 | final int usedTotal = getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin + 436 | heightUsed; 437 | final int childHeightMeasureSpec; 438 | if (lp.height == WRAP_CONTENT) { 439 | childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( 440 | Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - usedTotal), 441 | MeasureSpec.UNSPECIFIED); 442 | } else { 443 | childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 444 | getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin 445 | + heightUsed, lp.height); 446 | } 447 | child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 448 | } 449 | 450 | 451 | /** 452 | * 是否可以在水平方向上滚动 453 | * 举例: ViewPager 通过这个方法判断子 View 是否可以水平滚动,从而解决滑动冲突 454 | */ 455 | @Override 456 | public boolean canScrollHorizontally(int direction) { 457 | if (direction > 0) { 458 | return getScrollX() < getScrollRangeX(); 459 | } else { 460 | return getScrollX() > 0 && getScrollRangeX() > 0; 461 | } 462 | } 463 | 464 | /** 465 | * 是否可以在竖直方向上滚动 466 | * 举例: ViewPager 通过这个方法判断子 View 是否可以竖直滚动,从而解决滑动冲突 467 | */ 468 | @Override 469 | public boolean canScrollVertically(int direction) { 470 | if (direction > 0) { 471 | return getScrollY() < getScrollRangeY(); 472 | } else { 473 | return getScrollY() > 0 && getScrollRangeY() > 0; 474 | } 475 | } 476 | 477 | public void setZoomLayoutGestureListener(ZoomLayoutGestureListener zoomLayoutGestureListener) { 478 | mZoomLayoutGestureListener = zoomLayoutGestureListener; 479 | } 480 | 481 | public interface ZoomLayoutGestureListener { 482 | void onScrollBegin(); 483 | void onScaleGestureBegin(); 484 | void onDoubleTap(); 485 | } 486 | } -------------------------------------------------------------------------------- /library/src/main/res/values/attr.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /library/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | library 3 | 4 | -------------------------------------------------------------------------------- /library/src/test/java/com/xuliwen/zoom/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.xuliwen.zoom; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':library' 2 | rootProject.name='ZoomLayout' 3 | --------------------------------------------------------------------------------