Repository: jvziyaoyao/scale
Branch: main
Commit: 77dc2208614f
Files: 192
Total size: 556.1 KB
Directory structure:
gitextract_jlmm829s/
├── .gitignore
├── .idea/
│ ├── .name
│ ├── AndroidProjectSystem.xml
│ ├── artifacts/
│ │ ├── img.xml
│ │ ├── sampe_kmp.xml
│ │ ├── sample_kmp.xml
│ │ ├── sample_kmp_jvm.xml
│ │ ├── scale_image_viewer.xml
│ │ ├── scale_image_viewer_jvm.xml
│ │ ├── scale_sampling_decoder.xml
│ │ ├── scale_sampling_decoder_jvm.xml
│ │ ├── scale_sampling_decoder_kmp.xml
│ │ ├── scale_zoomable_view.xml
│ │ ├── scale_zoomable_view_js.xml
│ │ ├── scale_zoomable_view_jvm.xml
│ │ ├── scale_zoomable_view_wasm_js.xml
│ │ └── shared.xml
│ ├── compiler.xml
│ ├── deploymentTargetDropDown.xml
│ ├── deploymentTargetSelector.xml
│ ├── gradle.xml
│ ├── inspectionProfiles/
│ │ └── Project_Default.xml
│ ├── kotlinc.xml
│ ├── migrations.xml
│ ├── misc.xml
│ ├── runConfigurations.xml
│ ├── vcs.xml
│ └── xcode.xml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── build.gradle.kts
├── buildSrc/
│ ├── .gitignore
│ ├── build.gradle.kts
│ ├── settings.gradle.kts
│ └── src/
│ └── main/
│ └── kotlin/
│ └── scale/
│ ├── hierarchyTemplate.kt
│ └── util.kt
├── doc/
│ ├── assemble_dokka.sh
│ ├── change_index_path.py
│ ├── copy_root_doc.sh
│ ├── deploy_docs.sh
│ ├── docs/
│ │ ├── getting_started.md
│ │ ├── image_pager.md
│ │ ├── image_previewer.md
│ │ ├── image_viewer.md
│ │ ├── previewer.md
│ │ ├── sampling_decoder.md
│ │ ├── zoomable_pager.md
│ │ └── zoomable_view.md
│ ├── mkdocs.yml
│ └── run_doc_server.sh
├── gradle/
│ ├── libs.versions.toml
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── sample-android/
│ ├── .gitignore
│ ├── build.gradle.kts
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── jvziyaoyao/
│ │ └── image/
│ │ └── viewer/
│ │ └── ExampleInstrumentedTest.kt
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── jvziyaoyao/
│ │ │ └── scale/
│ │ │ └── sample/
│ │ │ ├── base/
│ │ │ │ ├── BaseActivity.kt
│ │ │ │ └── BasePermission.kt
│ │ │ ├── page/
│ │ │ │ ├── DecoderActivity.kt
│ │ │ │ ├── DuplicateActivity.kt
│ │ │ │ ├── GalleryActivity.kt
│ │ │ │ ├── HomeActivity.kt
│ │ │ │ ├── HugeActivity.kt
│ │ │ │ ├── NormalActivity.kt
│ │ │ │ ├── PicturesActivity.kt
│ │ │ │ ├── PreviewerActivity.kt
│ │ │ │ ├── TransformActivity.kt
│ │ │ │ └── ZoomableActivity.kt
│ │ │ └── ui/
│ │ │ ├── component/
│ │ │ │ ├── ImageLoader.kt
│ │ │ │ └── Layout.kt
│ │ │ └── theme/
│ │ │ ├── Color.kt
│ │ │ ├── Layout.kt
│ │ │ ├── Shape.kt
│ │ │ ├── Theme.kt
│ │ │ └── Type.kt
│ │ └── res/
│ │ ├── drawable/
│ │ │ ├── ic_dark_bg.xml
│ │ │ ├── ic_empty_image.xml
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── mipmap-anydpi-v26/
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── values/
│ │ │ ├── colors.xml
│ │ │ ├── ic_launcher_background.xml
│ │ │ ├── strings.xml
│ │ │ └── themes.xml
│ │ ├── values-night/
│ │ │ └── themes.xml
│ │ ├── values-v27/
│ │ │ └── themes.xml
│ │ └── xml/
│ │ └── network_security_config.xml
│ └── test/
│ └── java/
│ └── com/
│ └── jvziyaoyao/
│ └── image/
│ └── viewer/
│ └── ExampleUnitTest.kt
├── sample-ios/
│ ├── iosSample/
│ │ ├── Assets.xcassets/
│ │ │ ├── AccentColor.colorset/
│ │ │ │ └── Contents.json
│ │ │ ├── AppIcon.appiconset/
│ │ │ │ └── Contents.json
│ │ │ └── Contents.json
│ │ ├── ContentView.swift
│ │ ├── Preview Content/
│ │ │ └── Preview Assets.xcassets/
│ │ │ └── Contents.json
│ │ ├── component/
│ │ │ └── ComposeView.swift
│ │ ├── iosSampleApp.swift
│ │ └── page/
│ │ ├── HomeViewController.swift
│ │ └── NavigationPageView.swift
│ ├── iosSample.xcodeproj/
│ │ ├── project.pbxproj
│ │ ├── project.xcworkspace/
│ │ │ ├── contents.xcworkspacedata
│ │ │ └── xcuserdata/
│ │ │ └── jvziyaoyao.xcuserdatad/
│ │ │ ├── UserInterfaceState.xcuserstate
│ │ │ └── xcschemes/
│ │ │ └── xcschememanagement.plist
│ │ └── xcuserdata/
│ │ └── jvziyaoyao.xcuserdatad/
│ │ └── xcschemes/
│ │ ├── iosSample.xcscheme
│ │ └── xcschememanagement.plist
│ ├── iosSampleTests/
│ │ └── iosSampleTests.swift
│ └── iosSampleUITests/
│ ├── iosSampleUITests.swift
│ └── iosSampleUITestsLaunchTests.swift
├── sample-kmp/
│ ├── .gitignore
│ ├── build.gradle.kts
│ └── src/
│ ├── androidMain/
│ │ ├── AndroidManifest.xml
│ │ └── kotlin/
│ │ └── com/
│ │ └── jvziyaoyao/
│ │ └── scale/
│ │ └── sample/
│ │ └── base/
│ │ └── BaseMathod.android.kt
│ ├── commonMain/
│ │ └── kotlin/
│ │ └── com/
│ │ └── jvziyaoyao/
│ │ └── scale/
│ │ └── sample/
│ │ ├── base/
│ │ │ └── BaseMathod.kt
│ │ ├── page/
│ │ │ ├── Decoder.kt
│ │ │ ├── Duplicate.kt
│ │ │ ├── Gallery.kt
│ │ │ ├── Home.kt
│ │ │ ├── Huge.kt
│ │ │ ├── Normal.kt
│ │ │ ├── Previewer.kt
│ │ │ ├── Transform.kt
│ │ │ └── Zoomable.kt
│ │ ├── sample/
│ │ │ ├── ImagePagerSample.kt
│ │ │ ├── ImagePreviewerSample.kt
│ │ │ ├── ImageViewerSample.kt
│ │ │ ├── PreviewerSample.kt
│ │ │ ├── SamplingDecoderSample.kt
│ │ │ ├── ZoomablePagerSample.kt
│ │ │ └── ZoomableViewSample.kt
│ │ └── ui/
│ │ ├── component/
│ │ │ ├── ImageLoader.kt
│ │ │ └── ScaleGrid.kt
│ │ └── theme/
│ │ ├── Layout.kt
│ │ └── Theme.kt
│ └── iosMain/
│ └── kotlin/
│ └── com/
│ └── jvziyaoyao/
│ └── scale/
│ └── sample/
│ ├── ViewController.kt
│ └── base/
│ └── BaseMathod.ios.kt
├── scale-image-viewer/
│ ├── .gitignore
│ ├── build.gradle.kts
│ ├── gradle.properties
│ └── src/
│ └── commonMain/
│ └── kotlin/
│ └── com/
│ └── jvziyaoyao/
│ └── scale/
│ └── image/
│ ├── pager/
│ │ └── ImagePager.kt
│ ├── previewer/
│ │ ├── ImagePreviewer.kt
│ │ └── TransformImageView.kt
│ └── viewer/
│ └── ImageViewer.kt
├── scale-image-viewer-classic/
│ ├── .gitignore
│ ├── build.gradle.kts
│ ├── consumer-rules.pro
│ ├── gradle.properties
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── jvziyaoyao/
│ │ └── scale/
│ │ └── image/
│ │ └── classic/
│ │ └── ExampleInstrumentedTest.kt
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ └── java/
│ │ └── com/
│ │ └── origeek/
│ │ └── imageViewer/
│ │ ├── gallery/
│ │ │ └── ImageGallery.kt
│ │ ├── previewer/
│ │ │ ├── ImagePreviewer.kt
│ │ │ ├── ImageTransform.kt
│ │ │ ├── ImageViewerContainer.kt
│ │ │ ├── PreviewerPagerState.kt
│ │ │ ├── PreviewerTransformState.kt
│ │ │ └── PreviewerVerticalDragState.kt
│ │ ├── util/
│ │ │ └── Ticket.kt
│ │ └── viewer/
│ │ ├── ImageComposeCanvas.kt
│ │ ├── ImageComposeOrigin.kt
│ │ └── ImageViewer.kt
│ └── test/
│ └── java/
│ └── com/
│ └── jvziyaoyao/
│ └── scale/
│ └── image/
│ └── classic/
│ └── ExampleUnitTest.kt
├── scale-sampling-decoder/
│ ├── .gitignore
│ ├── build.gradle.kts
│ ├── gradle.properties
│ └── src/
│ ├── androidMain/
│ │ ├── AndroidManifest.xml
│ │ └── kotlin/
│ │ └── com/
│ │ └── jvziyaoyao/
│ │ └── scale/
│ │ └── image/
│ │ └── sampling/
│ │ └── RegionDecoder.android.kt
│ ├── commonMain/
│ │ └── kotlin/
│ │ └── com/
│ │ └── jvziyaoyao/
│ │ └── scale/
│ │ └── image/
│ │ └── sampling/
│ │ ├── BlockingDeque.kt
│ │ ├── RegionDecoder.kt
│ │ ├── SamplingCanvas.kt
│ │ ├── SamplingDecoder.kt
│ │ └── SamplingProcessor.kt
│ └── nonAndroidMain/
│ └── kotlin/
│ └── com/
│ └── jvziyaoyao/
│ └── scale/
│ └── image/
│ └── sampling/
│ └── RegionDecoder.nonAndroid.kt
├── scale-zoomable-view/
│ ├── .gitignore
│ ├── build.gradle.kts
│ ├── gradle.properties
│ └── src/
│ └── commonMain/
│ └── kotlin/
│ └── com/
│ └── jvziyaoyao/
│ └── scale/
│ └── zoomable/
│ ├── pager/
│ │ ├── Pager.kt
│ │ └── ZoomablePager.kt
│ ├── previewer/
│ │ ├── DraggablePreviewer.kt
│ │ ├── PopupPreviewer.kt
│ │ ├── Previewer.kt
│ │ ├── TransformItem.kt
│ │ └── TransformPreviewer.kt
│ ├── util/
│ │ ├── TextUtil.kt
│ │ └── TimeUtil.kt
│ └── zoomable/
│ ├── ZoomableGesture.kt
│ ├── ZoomableState.kt
│ └── ZoomableView.kt
└── settings.gradle.kts
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.iml
.gradle
.kotlin
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
/doc/docs/reference
/doc/docs/index.md
/doc/docs/change_log.md
/doc/site
================================================
FILE: .idea/.name
================================================
scale
================================================
FILE: .idea/AndroidProjectSystem.xml
================================================
================================================
FILE: .idea/artifacts/img.xml
================================================
$PROJECT_DIR$/img/build/libs
================================================
FILE: .idea/artifacts/sampe_kmp.xml
================================================
$PROJECT_DIR$/sampe-kmp/build/libs
================================================
FILE: .idea/artifacts/sample_kmp.xml
================================================
$PROJECT_DIR$/sample-kmp/build/libs
================================================
FILE: .idea/artifacts/sample_kmp_jvm.xml
================================================
$PROJECT_DIR$/sample-kmp/build/libs
================================================
FILE: .idea/artifacts/scale_image_viewer.xml
================================================
$PROJECT_DIR$/scale-image-viewer/build/libs
================================================
FILE: .idea/artifacts/scale_image_viewer_jvm.xml
================================================
$PROJECT_DIR$/scale-image-viewer/build/libs
================================================
FILE: .idea/artifacts/scale_sampling_decoder.xml
================================================
$PROJECT_DIR$/scale-sampling-decoder/build/libs
================================================
FILE: .idea/artifacts/scale_sampling_decoder_jvm.xml
================================================
$PROJECT_DIR$/scale-sampling-decoder/build/libs
================================================
FILE: .idea/artifacts/scale_sampling_decoder_kmp.xml
================================================
$PROJECT_DIR$/scale-sampling-decoder-kmp/build/libs
================================================
FILE: .idea/artifacts/scale_zoomable_view.xml
================================================
$PROJECT_DIR$/scale-zoomable-view/build/libs
================================================
FILE: .idea/artifacts/scale_zoomable_view_js.xml
================================================
$PROJECT_DIR$/scale-zoomable-view/build/libs
================================================
FILE: .idea/artifacts/scale_zoomable_view_jvm.xml
================================================
$PROJECT_DIR$/scale-zoomable-view/build/libs
================================================
FILE: .idea/artifacts/scale_zoomable_view_wasm_js.xml
================================================
$PROJECT_DIR$/scale-zoomable-view/build/libs
================================================
FILE: .idea/artifacts/shared.xml
================================================
$PROJECT_DIR$/shared/build/libs
================================================
FILE: .idea/compiler.xml
================================================
================================================
FILE: .idea/deploymentTargetDropDown.xml
================================================
================================================
FILE: .idea/deploymentTargetSelector.xml
================================================
================================================
FILE: .idea/gradle.xml
================================================
================================================
FILE: .idea/inspectionProfiles/Project_Default.xml
================================================
================================================
FILE: .idea/kotlinc.xml
================================================
================================================
FILE: .idea/migrations.xml
================================================
================================================
FILE: .idea/misc.xml
================================================
================================================
FILE: .idea/runConfigurations.xml
================================================
================================================
FILE: .idea/vcs.xml
================================================
================================================
FILE: .idea/xcode.xml
================================================
================================================
FILE: CHANGELOG.md
================================================
# **Change Log**
All notable changes to this project will be documented in this file.
## 1.1.1-beta.3 (Nov 22, 2025)
- Fix: Maven包添加Desktop Target;
- Fix: KotlinDateTime升级至0.7.1;
## 1.1.1-beta.2 (Jul 21, 2025)
- Feat: SamplingDecoder支持KMP;
- Feat: 移除LocalTransformItemStateMap;
- Fix: 动画进行中禁止页面手势;
## 1.1.1-beta.1 (Jun 25, 2025)
- Feat: Zoomable支持KMP;
- Feat: ImageViewer支持KMP;
- Fix: 移除底层对Material的依赖;
- Fix: 修复下拉关闭手势异常的问题;
- Fix: 修复图片未加载完成按返回退出页面的问题;
## 1.1.0-alpha.7 (Apr 18, 2025)
- Fix: 修复部分手机下拉关闭时闪烁的问题;
## 1.1.0-alpha.6 (Mar 7, 2025)
- Feat: Compose版本更新支持1.7.8;
## 1.1.0-alpha.5 (Aug 15, 2024)
- Feat: 根据当前环境获取transformItemStateMap;
- Feat: Pager、ImagePager增加是否允许滚动的参数;
- Feat: 限制动画进行时页面滚动;
- Fix: 修复animating状态需等图片加载完才标记结束的问题;
- Fix: 修复openTransform过程中偶发崩溃的问题;
- Fix: 修复页面快速切换导致图片不显示的问题;
## 1.1.0-alpha.4 (Jun 23, 2024)
- Fix: 修复PopupPreviewer显示与关闭完成状态不正确的问题;
## 1.1.0-alpha.3 (Jun 14, 2024)
- Fix: Compose回退到稳定版本1.6.8;
## 1.1.0-alpha.2 (Jun 9, 2024)
- Feat: 发布到MavenCentral;
- Feat: 增加ModelProcessor;
- Feat: ImageDecoder、ImageCanvas更名为SamplingDecoder、SamplingCanvas;
- Feat: 新增[使用文档](https://jvziyaoyao.github.io/scale/) 、[API文档](https://jvziyaoyao.github.io/scale/reference/);
- Feat: 更换开源协议为Apache2.0;
- Fix: 修复enterTransform后close小图未显示的问题;
- Fix: 修复ZoomablePager中state与页码不匹配的问题;
- Fix: 修复TransformPreviewer在缩放率大于1时关闭动画错乱的问题;
- Fix: 将Zoomable最大缩放比调整回4;
## 1.1.0-alpha.1 (May 25, 2024)
- Feat: 弃用com.origeek.imageViewer;
- Feat: 重构ImageViewer;
- Feat: 重构ImageGallery为ImagePager;
- Feat: 重构ImagePreviewer;
- Feat: 新增ZoomableView;
- Feat: 新增ZoomablePager;
- Feat: 新增Previewer;
## 1.0.2-alpha.8 (Dec 1, 2023)
- Feat: galleryState添加pageCount;
## 1.0.2-alpha.6 (Oct 8, 2023)
- Feat: 支持上下滑手势关闭图片预览;
## 1.0.2-alpha.5 (Aug 18, 2023)
- Feat: 适配到高版本的HorizontalPager;
## 1.0.2-alpha.4 (Jun 19, 2023)
- Fix: 修复imageDecoder release之后获取长宽导致崩溃的问题;
- Fix: 解决TransformItem在LazyList中不及时刷新的问题;
- Feat: 支持大图进行图片旋转;
- Feat: 重构ComposeModel部分以支持手势操作;
## 1.0.2-alpha.3 (May 12, 2023)
- Fix: 移除TransformImageView中的movable,提高滚动性能;
- Feat: Pager组件更新到官方的Pager;
## 1.0.2-alpha.2 (Jan 11, 2023)
- Fix: OrigeekUI切换到发布版本1.0.1-alpha.1
## 1.0.2-alpha.1 (Jan 10, 2023)
- Feat: 支持transform动画效果
- Feat: 支持viewer下拉关闭
- Feat: viewer支持placeholder
- Feat: 对自定义动画曲线提供更完善的支持
- Feat: Canvas大图组件增加淡入淡出效果
- Fix: 集成Viewer时不需要额外集成Pager
- Fix: 优化各组件的参数配置,提高代码简洁度
- Fix: 修复大图预览时卡顿的问题
- Fix: 修复各组件旋转屏幕时状态丢失的问题
## 1.0.1-alpha.3 (Oct 5, 2022)
- Fix crash caused by screen orientationn changed (#7)
## 1.0.1-alpha.2 (Jun 23, 2022)
- Create a sample for this library
## 1.0.1-alpha.1
- Create this repository and release the first version
================================================
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) 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
(d) 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 2022 jvziyaoyao
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
================================================
----
🖼 An image viewer for jetpack compose multiplatform.
一款基于`Jetpack Compose Multiplatform`开发的图片浏览库,支持过渡变换和超大图片的显示
The latest version:
### 🥳 1.1.1 全新版本~`Scale`支持`Multiplatform`啦!
#### 📓 开发文档 👉 [DOCS](https://jvziyaoyao.github.io/scale)
#### 📝 更新日志 👉 [CHANGELOG](/CHANGELOG.md)
#### 📑 产品与应用 👉 [小小检查单](https://www.origeek.com)
#### 👨💻 产品与开源 👉 [JVZIYAOYAO](https://www.jvziyaoyao.com)
🌟 案例
--------
#### 📷 RawCamera 👉 [GITHUB](https://github.com/jvziyaoyao/raw-camera)
#### 🌆 ImagePicker 👉 [GITHUB](https://github.com/jvziyaoyao/ImagePicker)
👌 特性
--------
- 基于Jetpack Compose Multiplatform开发;
- 符合直觉的手势动效;
- 支持超大图片显示;
- 提供图片列表浏览组件;
- 支持图片弹出预览组件;
- 支持图片弹出预览的过渡动画;
- 支持定制化可扩展性高;
- 不依赖第三方图片库;
🖇️ 跨平台
--------
| 兼容性 | Android | IOS | Desktop | JS/WasmJS |
|----------------------------|:--------:|:--------:|:-------:|:---------:|
| scale-zoomable-view | ✅ | ✅ | ✅ | ⛔️ |
| scale-image-viewer | ✅ | ✅ | ✅ | ⛔️ |
| scale-sampling-decoder | ✅ | ✅ | ✅ | ⛔️ |
| scale-image-viewer-classic | ⚠️废弃 | ⚠️废弃 | ⚠️废弃 | ⛔️ |
🧐 预览
--------
📓 API
--------
💽 接口文档 👉 [API REFERENCE](https://jvziyaoyao.github.io/scale/reference)
👓 示例
--------
👋 示例代码请参考:
Android 👉 [SAMPLE-ANDROID](https://github.com/jvziyaoyao/scale/tree/dev/sample/src/main/java/com/jvziyaoyao/scale/sample-android)
IOS 👉 [SAMPLE-IOS](https://github.com/jvziyaoyao/scale/tree/dev/sample/src/main/java/com/jvziyaoyao/scale/sample-ios)
🛒 引入
--------
Scale is available on `mavenCentral()`
```kotlin
// 使用MavenCentral仓库
repositories {
mavenCentral()
}
val version = "1.1.1-beta.3"
// 图片浏览库
implementation("com.jvziyaoyao.scale:image-viewer:$version")
// 大型图片支持(可选)
implementation("com.jvziyaoyao.scale:sampling-decoder:$version")
```
🛵 使用方式
--------
### 1️⃣ 缩放组件
```kotlin
val painter = painterResource(id = R.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ZoomableView(state = state) {
Image(
modifier = Modifier.fillMaxSize(), // 这里请务必要充满整个图层
painter = painter,
contentDescription = null,
)
}
```
### 2️⃣ 查看图片
```kotlin
val scope = rememberCoroutineScope()
val state = rememberZoomableState()
ImageViewer(
state = state,
model = painterResource(id = R.drawable.light_02),
modifier = Modifier.fillMaxSize(),
detectGesture = ZoomableGestureScope(onDoubleTap = {
// 双击放大缩小
scope.launch {
state.toggleScale(it)
}
})
)
```
### 3️⃣ 加载超大图
添加`SamplingDecoder`依赖支持:
```kotlin
implementation("com.jvziyaoyao.scale:sampling-decoder:$version")
```
‼ 仅在`model`类型为`SamplingDecoder`才会被当做大图进行加载
```kotlin
val bytes = remember { mutableStateOf(null) }
LaunchedEffect(Unit) { bytes.value = Res.readBytes("files/a350.jpg") }
val (samplingDecoder) = rememberSamplingDecoder(bytes.value)
if (samplingDecoder != null) {
val state = rememberZoomableState(
contentSize = samplingDecoder.intrinsicSize
)
ImageViewer(
model = samplingDecoder,
state = state,
processor = ModelProcessor(samplingProcessorPair),
)
}
```
### 4️⃣ 图片列表浏览
```kotlin
val images = remember {
mutableStateListOf(
R.drawable.light_01,
R.drawable.light_02,
)
}
ImagePager(
modifier = Modifier.fillMaxSize(),
pagerState = rememberZoomablePagerState { images.size },
imageLoader = { index ->
val painter = painterResource(images[index])
return@ImagePager Pair(painter, painter.intrinsicSize)
},
)
```
### 5️⃣ 图片弹出预览
```kotlin
val images = remember {
listOf(
R.drawable.img_01,
R.drawable.img_02,
)
}
val previewerState = rememberPreviewerState(pageCount = { images.size })
val scope = rememberCoroutineScope()
ImagePreviewer(
state = previewerState,
detectGesture = PagerGestureScope(onTap = {
scope.launch {
// 关闭预览组件
previewerState.close()
}
}),
imageLoader = { index ->
val painter = painterResource(id = images[index])
Pair(painter, painter.intrinsicSize)
}
)
// 显示预览组件
previewerState.open()
```
### 6️⃣ 图片弹出预览(带转换效果)
```kotlin
val images = remember {
listOf(
// 依次声明图片的key、缩略图、原图(实际情况按实际情况来,这里只是示例)
Triple("001", R.drawable.thumb_01, R.drawable.img_01),
Triple("002", R.drawable.thumb_02, R.drawable.img_02),
)
}
// 为组件提供获取数据长度和获取key的方法
val previewerState = rememberPreviewerState(
pageCount = { images.size },
getKey = { images[it].first }
)
// 显示缩略图小图的示例代码
val index = 1
val scope = rememberCoroutineScope()
TransformImageView(
modifier = Modifier
.size(120.dp)
.clickable {
scope.launch {
// 点击事件触发动效
previewerState.enterTransform(index)
}
},
imageLoader = {
val key = images[index].first
val imageDrawableId = images[index].second
val painter = painterResource(id = imageDrawableId) // 这里使用的是缩略图
// 必须依次返回key、图片数据、图片的尺寸
Triple(key, painter, painter.intrinsicSize)
},
transformState = previewerState,
)
// 这里声明图片预览组件
ImagePreviewer(
state = previewerState,
detectGesture = PagerGestureScope(onTap = {
scope.launch {
// 点击界面后关闭组件
previewerState.exitTransform()
}
}),
imageLoader = {
val painter = painterResource(id = images[it].third) // 这里使用的是原图
// 这里必须依次返回图片数据、图片的尺寸
return@ImagePreviewer Pair(painter, painter.intrinsicSize)
}
)
```
🕵️♀️ 开源许可
--------
Copyright 2022 jvziyaoyao
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: build.gradle.kts
================================================
import scale.versionName
plugins {
id("org.jetbrains.dokka")
}
tasks.dokkaHtmlMultiModule {
moduleName.set("Scale")
moduleVersion.set(project.versionName)
outputDirectory.set(file("$rootDir/doc/docs/reference"))
}
================================================
FILE: buildSrc/.gitignore
================================================
/build
================================================
FILE: buildSrc/build.gradle.kts
================================================
plugins {
`kotlin-dsl-base`
}
repositories {
google()
mavenCentral()
}
dependencies {
implementation(libs.gradle.plugin.android)
implementation(libs.gradle.plugin.jetbrains.compose)
implementation(libs.gradle.plugin.compose.compiler)
implementation(libs.gradle.plugin.kotlin)
implementation(libs.gradle.plugin.maven.publish)
implementation(libs.gradle.plugin.dokka)
}
================================================
FILE: buildSrc/settings.gradle.kts
================================================
rootProject.name = "scale"
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(files("../gradle/libs.versions.toml"))
}
}
}
pluginManagement {
plugins {
id("org.jetbrains.kotlin.android") version "2.1.0"
id("com.android.library") version "8.4.0"
}
repositories {
google()
gradlePluginPortal()
mavenCentral()
}
}
================================================
FILE: buildSrc/src/main/kotlin/scale/hierarchyTemplate.kt
================================================
@file:OptIn(ExperimentalKotlinGradlePluginApi::class)
package scale
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.plugin.KotlinHierarchyBuilder
import org.jetbrains.kotlin.gradle.plugin.KotlinHierarchyTemplate
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSetTree
private val hierarchyTemplate = KotlinHierarchyTemplate {
withSourceSetTree(
KotlinSourceSetTree.main,
KotlinSourceSetTree.test,
)
common {
withCompilations { true }
groupNonAndroid()
groupJsCommon()
groupNonJsCommon()
groupJvmCommon()
groupNonJvmCommon()
groupNative()
groupNonNative()
}
}
private fun KotlinHierarchyBuilder.groupNonAndroid() {
group("nonAndroid") {
withJvm()
groupJsCommon()
groupNative()
}
}
private fun KotlinHierarchyBuilder.groupJsCommon() {
group("jsCommon") {
withJs()
withWasmJs()
}
}
private fun KotlinHierarchyBuilder.groupNonJsCommon() {
group("nonJsCommon") {
groupJvmCommon()
groupNative()
}
}
private fun KotlinHierarchyBuilder.groupJvmCommon() {
group("jvmCommon") {
withAndroidTarget()
withJvm()
}
}
private fun KotlinHierarchyBuilder.groupNonJvmCommon() {
group("nonJvmCommon") {
groupJsCommon()
groupNative()
}
}
private fun KotlinHierarchyBuilder.groupNative() {
group("native") {
withNative()
group("apple") {
withApple()
group("ios") {
withIos()
}
group("macos") {
withMacos()
}
}
}
}
private fun KotlinHierarchyBuilder.groupNonNative() {
group("nonNative") {
groupJsCommon()
groupJvmCommon()
}
}
fun KotlinMultiplatformExtension.applyScaleHierarchyTemplate() {
applyHierarchyTemplate(hierarchyTemplate)
}
================================================
FILE: buildSrc/src/main/kotlin/scale/util.kt
================================================
package scale
import org.gradle.api.Project
val Project.minSdk: Int
get() = project.properties["minSdk"].toString().toInt()
val Project.targetSdk: Int
get() = project.properties["targetSdk"].toString().toInt()
val Project.compileSdk: Int
get() = project.properties["compileSdk"].toString().toInt()
val Project.versionName: String
get() = project.properties["VERSION_NAME"].toString()
================================================
FILE: doc/assemble_dokka.sh
================================================
set -e
rm -rf docs/reference
../gradlew -p ../ clean dokkaHtmlMultiModule
================================================
FILE: doc/change_index_path.py
================================================
import os
target_file = 'docs/index.md'
with open(target_file, 'r') as src:
content = src.read()
content = content.replace('doc/docs/image/', 'image/')
content = content.replace('/CHANGELOG.md', 'change_log.md/')
with open(target_file, 'w') as tgt:
tgt.write(content)
================================================
FILE: doc/copy_root_doc.sh
================================================
rm -rf docs/index.md
rm -rf docs/change_log.md
cp ../README.md docs/index.md
cp ../CHANGELOG.md docs/change_log.md
python3 change_index_path.py
================================================
FILE: doc/deploy_docs.sh
================================================
# 刷新dokka文档
./assemble_dokka.sh
# 复制首页的文档
./copy_root_doc.sh
# 发布到分支
python3 -m mkdocs gh-deploy --force
================================================
FILE: doc/docs/getting_started.md
================================================
# Getting Started
## 📦 Artifacts
`Scale`使用`mavenCentral()`进行分发,包含以下四个模块:
* `com.jvziyaoyao.scale:image-viewer` 提供了图片放大缩小、列表浏览、弹出预览组件和动效的图片浏览库,开箱即用
* `com.jvziyaoyao.scale:zoomable-view` `ImageViewer`的基础库,包含`ZoomableView`、`ZoomablePager`、`Previewer`,具有较高的扩展性
* `com.jvziyaoyao.scale:sampling-decoder` 提供了对大型图片进行二次采样显示的支持
* `com.jvziyaoyao.scale:image-viewer-classic` 老版本`ImageViewer`
## 🖼️ ImageViewer
对一张图片进行放大缩小:
```kotlin
val painter = painterResource(id = R.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ImageViewer(model = painter, state = state)
```
## 🔎 ZoomableView
对任意一个Composable进行放大缩小:
```kotlin
val painter = painterResource(id = R.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ZoomableView(state = state) {
Image(
modifier = Modifier.fillMaxSize(), // 这里请务必要充满整个图层
painter = painter,
contentDescription = null,
)
}
```
## 💽 SamplingDecoder
对大型图片进行二次采样:
```kotlin
val context = LocalContext.current
val inputStream = remember { context.assets.open("a350.jpg") }
val (samplingDecoder) = rememberSamplingDecoder(inputStream = inputStream)
if (samplingDecoder != null) {
val state = rememberZoomableState(
contentSize = samplingDecoder.intrinsicSize
)
ImageViewer(
model = samplingDecoder,
state = state,
processor = ModelProcessor(samplingProcessorPair)
)
}
```
## 🎞️ ImagePager
展示图片列表:
```kotlin
val images = remember {
mutableStateListOf(R.drawable.light_01, R.drawable.light_02)
}
val pagerState = rememberZoomablePagerState { images.size }
ImagePager(
pagerState = pagerState,
imageLoader = { page ->
val painter = painterResource(id = images[page])
Pair(painter, painter.intrinsicSize)
}
)
```
## 📖 ImagePreviewer
图片弹出预览:
```kotlin
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val state = rememberPreviewerState(pageCount = { images.size }) { images[it] }
ImagePreviewer(
state = state,
imageLoader = { page ->
val painter = rememberAsyncImagePainter(model = images[page])
Pair(painter, painter.intrinsicSize)
}
)
// 展开
state.open()
// 关闭
state.close()
```
支持过渡动画:
```kotlin
Row {
images.forEachIndexed { index, url ->
TransformImageView(
modifier = Modifier
.size(120.dp)
.clickable {
scope.launch {
state.enterTransform(index)
}
},
imageLoader = {
val painter = rememberAsyncImagePainter(model = url)
Triple(url, painter, painter.intrinsicSize)
},
transformState = state,
)
}
}
```
================================================
FILE: doc/docs/image_pager.md
================================================
# ImagePager
`ImagePager`是一个展示图片列表的组件
## 🥃 简单使用
```kotlin
val images = remember {
mutableStateListOf(R.drawable.light_01, R.drawable.light_02)
}
val pagerState = rememberZoomablePagerState { images.size }
ImagePager(
pagerState = pagerState,
imageLoader = { page ->
val painter = painterResource(id = images[page])
Pair(painter, painter.intrinsicSize)
}
)
```
## 🍷 结合Coil使用
```kotlin
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val pagerState = rememberZoomablePagerState { images.size }
ImagePager(
pagerState = pagerState,
imageLoader = { page ->
val painter = rememberAsyncImagePainter(model = images[page])
Pair(painter, painter.intrinsicSize)
}
)
```
## 🥂 ProceedPresentation
在`imageLoader`中,要求返回一个`Pair`类型的数据,第一个是图片数据,第二个为图片的固有大小,组件会根据两个数据的状态来判断是显示图片还是`loading`,这个逻辑可以通过复写`proceedPresentation`来修改
```kotlin
// 声明一个ProceedPresentation
val myProceedPresentation: ProceedPresentation =
{ model, size, processor, imageLoading ->
if (model != null && model is AnyComposable && size == null) {
model.composable.invoke()
true
} else if (model != null && size != null) {
ZoomablePolicy(intrinsicSize = size) {
processor.Deploy(model = model, state = it)
}
size.isSpecified
} else {
imageLoading?.invoke()
false
}
}
// 设置参数proceedPresentation
ImagePager(
proceedPresentation = myProceedPresentation
)
```
## 🍸 自定义loading
```kotlin
ImagePager(
imageLoading = {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center),
color = Color.Blue,
)
}
}
)
```
## 🍹 页面自定义
```kotlin
ImagePager(
pageDecoration = { page, innerPage ->
Box(modifier = Modifier.background(Color.LightGray)) {
innerPage.invoke()
// 设置每一页的前景图层
Box(
modifier = Modifier
.padding(bottom = 20.dp)
.clip(RoundedCornerShape(8.dp))
.background(Color.White)
.padding(8.dp)
.align(Alignment.BottomCenter),
) {
Text(text = "${page + 1}/${images.size}")
}
}
}
)
```
## 🍶 类型拓展
`ImagePager`可以通过`ModelProcessor`增加`model`支持的类型,参考文档:[`ImageViewer 类型拓展`](image_viewer.md#imageviewermodelprocessor)
## 🧉 手势回调
ImagePager手势监听与ZoomablePager一样,使用PagerGestureScope,参考文档:[`ZoomablePager PagerGestureScope`](zoomable_pager.md#pagergesturescope)
## 🥛 状态控制
ImagePager通过ZoomablePagerState进行状态控制,请参考文档:[`ZoomablePager ZoomablePagerState`](zoomable_pager.md#zoomablepagerstate)
================================================
FILE: doc/docs/image_previewer.md
================================================
# ImagePreviewer
通过`ImagePreviewer`可以很方便地实现一个类似微信朋友圈放大查看图片的组件
## 🌭 基本用法
```kotlin
// 准备一个图片列表
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
// 声明一个PreviewerState
val state = rememberPreviewerState(pageCount = { images.size }) { images[it] }
// 创建一个ImagePreviewer
ImagePreviewer(
state = state,
imageLoader = { page ->
val painter = rememberAsyncImagePainter(model = images[page])
Pair(painter, painter.intrinsicSize)
}
)
// 展开
state.open()
// 关闭
state.close()
```
## 🍔 过渡动效
使用`TransformImageView`替代`Image`,点击图片,图片放大并进入到预览列表
```kotlin
Box(modifier = Modifier.fillMaxSize()) {
Row(
modifier = Modifier.align(Alignment.Center),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
images.forEachIndexed { index, url ->
TransformImageView(
modifier = Modifier
.size(120.dp)
.clickable {
scope.launch {
state.enterTransform(index)
}
},
imageLoader = {
val painter = rememberAsyncImagePainter(model = url)
Triple(url, painter, painter.intrinsicSize)
},
transformState = state,
)
}
}
}
```
如上述代码所示,`TransformImageView`的`imageLoader`需要返回一个`Triple`类型的数据,
其中第一个参数为`key`,第二个为显示的图片数据,第三个为图片的固有大小
⚠️‼️ 注意`Key`与`Index`的一致性
```kotlin
val images = remember {
mutableStateListOf(
// key to image
"001" to R.drawable.img_01,
"002" to R.drawable.img_02,
)
}
val state = rememberPreviewerState(
pageCount = { images.size },
getKey = { index -> images[index].first } // 获取key
)
images.forEachIndexed { index, image ->
TransformImageView(
imageLoader = {
val painter = painterResource(id = image.second)
// key model size
Triple(image.first, painter, painter.intrinsicSize)
}
)
}
// index要与key的position一致
state.enterTransform(index)
```
在同一个界面中,如果存在同一个`key`同时出现在不同的部位时,此时使用弹出动画会导致动画位置不符合预期的情况,可以通过指定`ItemStateMap`的方式来解决
```kotlin
val imageIds = remember { listOf(R.drawable.img_03, R.drawable.img_06) }
val itemStateMap01 = remember { mutableStateMapOf() }
val previewerState01 = rememberPreviewerState(
transformItemStateMap = itemStateMap01,
pageCount = { imageIds.size },
getKey = { imageIds[it] },
)
val itemStateMap02 = remember { mutableStateMapOf() }
val previewerState02 = rememberPreviewerState(
transformItemStateMap = itemStateMap02,
pageCount = { imageIds.size },
getKey = { imageIds[it] },
)
CompositionLocalProvider(LocalTransformItemStateMap provides itemStateMap01) {
imageIds.forEach {
ImagePreviewer(
state = previewerState01,
imageLoader = { }
)
}
}
CompositionLocalProvider(LocalTransformItemStateMap provides itemStateMap02) {
imageIds.forEach {
ImagePreviewer(
state = previewerState02,
imageLoader = { }
)
}
}
```
如果`TransformImageView`无法满足功能需求时,可以考虑使用`TransformItemView`,使用方式见文档:[`Previewer 过渡动效`](previewer.md#transformitemview)
## 🥪 编辑图层
在`ImagePreviewer`中,设置`previewerLayer`来编辑`Previewer`的图层,通过`pageDecoration`来控制每一页的显示,
这里需要注意的是,`pageDecoration`要求返回一个`Boolean`类型的值,这个值可以通过调用`pageDecoration`传入的参数`innerPage`来获得
```kotlin
ImagePreviewer(
state = state,
imageLoader = { page ->
val painter = rememberAsyncImagePainter(model = images[page])
Pair(painter, painter.intrinsicSize)
},
pageDecoration = { _, innerPage ->
var mounted = false
// 单独设置每一页的背景颜色
Box(modifier = Modifier.background(Color.Cyan.copy(0.2F))) {
// 通过调用页面获取imageLoader的状态
mounted = innerPage()
// 设置前景图层
Box(
modifier = Modifier
.padding(bottom = 48.dp)
.size(56.dp)
.shadow(4.dp, CircleShape)
.background(Color.White)
.align(Alignment.BottomCenter),
) {
Text(
modifier = Modifier.align(Alignment.Center),
fontSize = 36.sp,
text = "❤️",
)
}
}
// 这里需要返回页面的挂载情况
mounted
},
previewerLayer = TransformLayerScope(
previewerDecoration = { innerPreviewer ->
// 设置ImagePreviewer的背景颜色
Box(
modifier = Modifier
.background(Color.Black)
) {
innerPreviewer.invoke()
}
}
),
)
```
## 🌮 类型拓展
`ImagePreviewer`可以通过`ModelProcessor`增加`model`支持的类型,参考文档:[`ImageViewer 类型拓展`](image_viewer.md#imageviewermodelprocessor)
## 🌯 Previewer
`ImagePreviewer`是基于`Previewer`封装而来的,其参数设置、状态控制、手势回调等用法一致,详情可参考文档:[`Previewer 基本配置`](previewer.md#previewersetting)
================================================
FILE: doc/docs/image_viewer.md
================================================
# ImageViewer
`ImageViewer`是一个图片放大缩小查看的组件,提供了默认配置,简化组件的使用流程
## 🍭 基本使用
```kotlin
val painter = painterResource(id = R.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ImageViewer(model = painter, state = state)
```
⚠️ ‼️ 这里需要注意的是,提供图片的固有尺寸是必须的,没有的话`ImageViewer`不会正常显示
## 🍰 结合Coil使用
```kotlin
val painter = rememberAsyncImagePainter(model = R.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ImageViewer(model = painter, state = state)
```
## 🍨 自定义内容
`ImageViewer`通过传人的`model`类型来自动选择使用何种方式进行图片显示,与`Image`类似,默认支持`Painter`、`ImageBitmap`、`ImageVector`,也支持通过`AnyComposable`传入一个`Composable`
```kotlin
// 设定显示内容的固有大小
val rectSize = 100.dp
val density = LocalDensity.current
val rectSizePx = density.run { rectSize.toPx() }
val size = Size(rectSizePx, rectSizePx)
val state = rememberZoomableState(contentSize = size)
ImageViewer(
state = state,
model = AnyComposable {
// 自定义内容
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Cyan)
) {
Box(
modifier = Modifier
.fillMaxSize(0.6F)
.clip(CircleShape)
.background(Color.White)
.align(Alignment.BottomEnd)
)
Text(
modifier = Modifier.align(Alignment.Center),
text = "Hello Compose"
)
}
}
)
```
但是,事实上这里并不推荐使用`AnyComposable`,`ImageViewer`是对`ZoomableView`进行封装而来,有较高的定制化需求可以考虑直接使用 [`ZoomableView`](zoomable_view.md)
## 🧁 类型拓展
`ImageViewer`可以通过`ModelProcessor`增加`model`支持的类型
```kotlin
val stringProcessorPair: ModelProcessorPair = String::class to { model, _ ->
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.LightGray)
) {
Text(
modifier = Modifier.align(Alignment.Center),
text = model as String
)
}
}
```
如上述代码所示,声明一个`ModelProcessorPair`,类型为`Pair Unit>`,
即传入`String`类型的`model`时,将按此方式进行显示
```kotlin
val message = "好家伙"
val state = rememberZoomableState(contentSize = Size(100F, 100F))
ImageViewer(
model = message,
state = state,
processor = ModelProcessor(stringProcessorPair)
)
```
`Scale`提供了对大型图片二次采样的支持,详情见文档:[`SamplingDecoder`](sampling_decoder.md)
```kotlin
ImageViewer(
processor = ModelProcessor(samplingProcessorPair)
)
```
## 🍦 手势与状态
`ImageViewer`手势事件回调为`ZoomableGestureScope`,状态与控制使用`ZoomableViewState`,见文档 [`ZoomableView ZoomableGestureScope ZoomableViewState`](zoomable_view.md#zoomablegesturescope)
================================================
FILE: doc/docs/previewer.md
================================================
# Previewer
`Scale`提供了一个`Previewer`组件,用以帮助开发者实现图片弹出预览的功能,
同时提供了类似微信朋友圈图片放大查看的过渡动画效果
## 🧀 简单使用
```kotlin
// 准备一个图片列表
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
// 声明一个PreviewerState
val state = rememberPreviewerState(pageCount = { images.size }) { images[it] }
// 创建一个Previewer
Previewer(
state = state,
) { page ->
val painter = rememberAsyncImagePainter(model = images[page])
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
painter.intrinsicSize.isSpecified
}
// 展开
state.open()
// 关闭
state.close()
```
## 🍞 过渡动效
过渡动效依赖`TransformItemView`,预览组件展开时,会按照 `TransformItemView -> Previewer`
的顺序进行`UI`变换,请确保`PreviewerState`中提供的`Key`与`TransformItemView`设置的`Key`一致,
通过调用`PreviewerState.enterTransform`展开,`PreviewerState.exitTransform`关闭
```kotlin
val scope = rememberCoroutineScope()
Box(modifier = Modifier.fillMaxSize()) {
Row(
modifier = Modifier.align(Alignment.Center),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
images.forEachIndexed { index, url ->
val painter = rememberAsyncImagePainter(model = url)
val itemState = rememberTransformItemState(
intrinsicSize = painter.intrinsicSize
)
TransformItemView(
modifier = Modifier
.size(120.dp)
.clickable {
scope.launch {
state.enterTransform(index)
}
},
key = url,
transformState = state,
itemState = itemState,
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
contentScale = ContentScale.Crop
)
}
}
}
}
```
⚠️‼️ 注意`Key`与`Index`的一致性
```kotlin
val images = remember {
mutableStateListOf(
// key to image
"001" to R.drawable.img_01,
"002" to R.drawable.img_02,
)
}
val state = rememberPreviewerState(
pageCount = { images.size },
getKey = { index -> images[index].first } // 获取key
)
images.forEachIndexed { index, image ->
TransformItemView(
key = image.first, // 设置key
)
}
// index要与key的position一致
state.enterTransform(index)
```
在同一个界面中,如果存在同一个`key`同时出现在不同的部位时,此时使用弹出动画会导致动画位置不符合预期的情况,可以通过指定`ItemStateMap`的方式来解决
```kotlin
val imageIds = remember { listOf(R.drawable.img_03, R.drawable.img_06) }
val itemStateMap01 = remember { mutableStateMapOf() }
val previewerState01 = rememberPreviewerState(
transformItemStateMap = itemStateMap01,
pageCount = { imageIds.size },
getKey = { imageIds[it] },
)
val itemStateMap02 = remember { mutableStateMapOf() }
val previewerState02 = rememberPreviewerState(
transformItemStateMap = itemStateMap02,
pageCount = { imageIds.size },
getKey = { imageIds[it] },
)
CompositionLocalProvider(LocalTransformItemStateMap provides itemStateMap01) {
imageIds.forEach {
TransformItemView(key = it) { }
}
}
CompositionLocalProvider(LocalTransformItemStateMap provides itemStateMap02) {
imageIds.forEach {
TransformItemView(key = it) { }
}
}
```
## 🥯 编辑图层
在`Previewer`中,设置`previewerLayer`来编辑`Previewer`的图层,通过`zoomablePolicy`来控制每一页的显示
```kotlin
Previewer(
state = state,
previewerLayer = TransformLayerScope(
previewerDecoration = {
// 设置组件的背景图层
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(0.2F))
) {
// 组件内容本身
it.invoke()
// 设置前景图层
Box(
modifier = Modifier
.padding(bottom = 48.dp)
.size(56.dp)
.shadow(4.dp, CircleShape)
.background(Color.White)
.align(Alignment.BottomCenter),
) {
Text(
modifier = Modifier.align(Alignment.Center),
fontSize = 36.sp,
text = "❤️",
)
}
}
},
),
) { page ->
val painter = rememberAsyncImagePainter(model = images[page])
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
if (!painter.intrinsicSize.isSpecified) {
// 加载中
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center)
)
}
}
painter.intrinsicSize.isSpecified
}
```
## 🥐 基本配置
可以通过`itemSpacing`设置每一页的间隙,`beyondViewportPageCount`设置预加载的页数,展开时,
如果不使用转换动效,可以设置展开和关闭动画,与`AnimatedVisibility`的使用方式一样
```kotlin
Previewer(
itemSpacing = 20.dp, // 设置页面的间隙
beyondViewportPageCount = 2, // 除当前页面外,预先加载其他页面的数量
enter = fadeIn(), // 展开动画
exit = fadeOut(), // 关闭动画
)
```
展开预览后,在缩放率为`1`的情况下,支持垂直方向上的手势操作,例如上下拖拽关闭预览
```kotlin
val previewerState = rememberPreviewerState(
verticalDragType = VerticalDragType.Down, // 设置垂直手势类型
pageCount = { images.size },
getKey = { images[it] }
)
```
## 🥞 手势回调
Previewer手势监听与ZoomablePager一样,使用PagerGestureScope,参考文档:[`ZoomablePager PagerGestureScope`](zoomable_pager.md#pagergesturescope)
## 🍕 状态控制
`PreviewerState`可以获取`Previewer`的各种状态参数,也可以通过代码来控制展开和关闭
```kotlin
previewerState.open() // 展开
previewerState.close() // 关闭
previewerState.enterTransform(0) // 带转换动画展开
previewerState.exitTransform() // 带转换动画关闭
previewerState.visible // 当前组件是否可见
previewerState.visibleTarget // 当前组件可见状态的目标值
previewerState.animating // 是否正在进行动画
previewerState.canOpen // 是否允许展开
previewerState.canClose // 是否允许关闭
```
================================================
FILE: doc/docs/sampling_decoder.md
================================================
# SamplingDecoder
`Scale`提供了`SamplingDecoder`、`SamplingCanvas`用于实现超级大图的预览,`SamplingDecoder`对`BitmapRegionDecoder`进行了封装,有助于开发者通过简单的`API`调用实现大型图片的加载显示,避免`OOM`
添加`SamplingDecoder`依赖支持:
```kotlin
implementation("com.jvziyaoyao.scale:sampling-decoder:$version")
```
## 🍋 简单使用
```kotlin
val context = LocalContext.current
val inputStream = remember { context.assets.open("a350.jpg") }
val (samplingDecoder) = rememberSamplingDecoder(inputStream = inputStream)
if (samplingDecoder != null) {
val state = rememberZoomableState(
contentSize = samplingDecoder.intrinsicSize
)
ImageViewer(
model = samplingDecoder,
state = state,
// 添加SamplingDecoder的支持
processor = ModelProcessor(samplingProcessorPair)
)
}
```
`SamplingDecoder`支持常见位图,如:`JPEG`、`PNG`、`HEIF`等,`RAW`、`GIF`这些并不支持,在使用`rememberSamplingDecoder`方法时,格式无法解析时会返回异常
```kotlin
// exception为报错信息
val (samplingDecoder,exception) =
rememberSamplingDecoder(inputStream = inputStream)
```
也可以自行创建一个`SamplingDecoder`,不过在组件销毁的时候务必要把`SamplingDecoder`移除,否则将导致内存泄漏
```kotlin
val bitmapRegionDecoder = // 创建一个BitmapRegionDecoder
val samplingDecoder =
createSamplingDecoder(decoder, SamplingDecoder.Rotation.ROTATION_0)
// 组件退出的时候release
DisposableEffect(Unit) {
onDispose {
samplingDecoder.release()
}
}
```
`SamplingDecoder`支持对图片进行旋转操作,例如某些文件会将旋转信息写到`Exif`中,请参考以下代码:
```kotlin
val file = // 图片文件
val inputStream = FileInputStream(file)
val exifInterface = ExifInterface(file)
val rotation = exifInterface.getDecoderRotation()
val samplingDecoder = rememberSamplingDecoder(inputStream, rotation)
```
## 🍊 在ZoomableView中使用
```kotlin
val state = rememberZoomableState(contentSize = samplingDecoder.intrinsicSize)
ZoomableView(state = state) {
SamplingCanvas(
samplingDecoder = samplingDecoder,
viewPort = state.getViewPort()
)
}
```
## 🍐 直接使用SamplingCanvas
```kotlin
val context = LocalContext.current
val inputStream = remember { context.assets.open("a350.jpg") }
val (samplingDecoder) = rememberSamplingDecoder(inputStream = inputStream)
if (samplingDecoder != null) {
val offset = remember { mutableStateOf(Offset.Zero) }
val scale = remember { mutableStateOf(1F) }
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, _, _ ->
offset.value += pan
scale.value *= zoom
true
}
}
) {
val ratio = samplingDecoder.intrinsicSize.run {
width.div(height)
}
Box(
modifier = Modifier
.graphicsLayer {
translationX = offset.value.x
translationY = offset.value.y
scaleX = scale.value
scaleY = scale.value
}
.fillMaxWidth()
.aspectRatio(ratio)
.align(Alignment.Center)
) {
SamplingCanvas(
samplingDecoder = samplingDecoder,
viewPort = SamplingCanvasViewPort(
scale = 8F,
visualRect = Rect(0.4F, 0.4F, 0.6F, 0.8F)
)
)
}
}
}
```
================================================
FILE: doc/docs/zoomable_pager.md
================================================
# ZoomablePager
`ZoomablePager`基于`ZoomableView`和`Jetpack Compose Pager`实现,提供对横向列表类型界面的支持,简化了手势处理和`ZoomableView`状态的持有
## 🍙 简单使用
```kotlin
// 准备一个图片列表
val images = remember {
mutableStateListOf(R.drawable.light_01, R.drawable.light_02)
}
// 创建一个PagerState
val pagerState = rememberZoomablePagerState { images.size }
// Pager组件
ZoomablePager(state = pagerState) { page ->
val painter = painterResource(id = images[page])
// 必须要调用的Composable函数
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) { _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
}
```
`ZoomablePolicy`方法对`ZoomableView`以及`ZoomableViewState`进行了一层封装,与`ZoomableView`的使用方式类似,必须要为`ZoomablePolicy`提供其中展示内容的固有大小,并且`ZoomablePolicy`的`content`中放置的`Composable`需要设置`Modifier.fillMaxSize()`
## 🍥 通过Coil展示网络图片
```kotlin
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val pagerState = rememberZoomablePagerState { images.size }
ZoomablePager(state = pagerState) { page ->
val painter = rememberAsyncImagePainter(model = images[page])
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) { _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
if (!painter.intrinsicSize.isSpecified) {
// 未加载成功时可以先显示一个loading占位
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center)
)
}
}
}
```
在使用`Coil`的过程中,某些特殊的写法可能会导致组件不可用:
```kotlin
// ❌ 错误示范
ZoomablePager(state = pagerState) { page ->
val painter = rememberAsyncImagePainter(model = images[page])
if (painter.intrinsicSize.isSpecified) {
// 以下代码将永远不会被执行
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) { _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
}
}
// ⭕️ 正确写法
ZoomablePager(state = pagerState) { page ->
val imageRequest = ImageRequest.Builder(LocalContext.current)
.data(images[page])
.size(coil.size.Size.ORIGINAL) // 指定获取图片的大小
.build()
val painter = rememberAsyncImagePainter(imageRequest)
if (painter.intrinsicSize.isSpecified) {
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) { _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
}
}
```
## 🍘 对页面自定义
```kotlin
ZoomablePager(state = pagerState) { page ->
val painter = painterResource(id = images[page])
// 设置背景色奇偶页不同
val backgroundColor = if (page % 2 == 0) Color.Cyan else Color.Gray
Box(
modifier = Modifier
.fillMaxSize()
.background(backgroundColor.copy(0.2F))
) {
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) { _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
// 设置每一页的前景图层
Box(
modifier = Modifier
.padding(bottom = 20.dp)
.clip(RoundedCornerShape(8.dp))
.background(Color.LightGray)
.padding(8.dp)
.align(Alignment.BottomCenter),
) {
Text(text = "${page + 1}/${images.size}")
}
}
}
```
与`Pager`一样,可以通过`itemSpacing`设置每一页的间隙,`beyondViewportPageCount`设置预加载的页数,`userScrollEnabled`设置是否允许用户滚动页面:
```kotlin
ZoomablePager(
itemSpacing = 20.dp, // 设置页面的间隙
beyondViewportPageCount = 2, // 除当前页面外,预先加载其他页面的数量
userScrollEnabled = true, // 允许用户滚动页面
) { }
```
----
`ZoomablePager`通过`PagerGestureScope`获取手势事件的回调,与`ZoomableView`类似,目前仅支持`onTap`、`onDoubleTap`、`onLongPress`
## 🍣 PagerGestureScope
```kotlin
ZoomablePager(
state = pagerState,
detectGesture = PagerGestureScope(
onTap = {
// 点击事件
},
onDoubleTap = {
// 双击事件
// 如果返回false,会执行默认操作,把当前页面放大到最大
// 如果返回true,则不会有任何操作
return@PagerGestureScope false
},
onLongPress = {
// 长按事件
}
)
) { }
```
## 🍤 ZoomablePagerState
`ZoomablePagerState`可以获取`ZoomablePager`的各种状态参数,也可以通过代码来切换当前页面:
```kotlin
val pagerState = rememberZoomablePagerState { images.size }
// 获取当前页面的页码
pagerState.currentPage
// 动画滚动到下一个页面
pagerState.animateScrollToPage(1)
// 滚动到下一个页面
pagerState.scrollToPage(1)
```
================================================
FILE: doc/docs/zoomable_view.md
================================================
# ZoomableView
`ZoomableView`是这个库最基本的组件,通过`ZoomableView`可以对任意`Composable`进行放大、缩小等操作
## 🥑 简单使用
```kotlin
val painter = painterResource(id = R.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ZoomableView(state = state) {
Image(
modifier = Modifier.fillMaxSize(), // 这里请务必要充满整个图层
painter = painter,
contentDescription = null,
)
}
```
在使用`ZoomableView`时,必须为组件提供一个`ZoomableViewState`,并且告知组件需要显示的内容的固有大小,否则组件不会正常显示
## 🍑 结合Coil使用
```kotlin
val painter = rememberAsyncImagePainter(model = R.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ZoomableView(state = state) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
)
}
```
`ZoomableView`会根据`ZoomableViewState`中获得的尺寸大小,将内容缩放到刚好能够完全显示,在`ZoomableView`的`content`中放置内容时需要为`Composable`设置`Modifier.fillMaxSize()`,否则会导致显示出问题
## 🍉 展示一个Composable
```kotlin
val density = LocalDensity.current
val rectSize = 100.dp
val rectSizePx = density.run { rectSize.toPx() }
val size = Size(rectSizePx, rectSizePx)
val state = rememberZoomableState(contentSize = size)
ZoomableView(state = state) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Cyan)
) {
Box(
modifier = Modifier
.fillMaxSize(0.6F)
.clip(CircleShape)
.background(Color.White)
.align(Alignment.BottomEnd)
)
Text(
modifier = Modifier.align(Alignment.Center),
text = "Hello Compose"
)
}
}
```
------
需要从`ZoomableView`获取手势事件的回调,可以使用`ZoomableGestureScope`,目前仅支持`onTap`、`onDoubleTap`、`onLongPress`
## 🥥 ZoomableGestureScope
```kotlin
ZoomableView(
state = rememberZoomableState(),
detectGesture = ZoomableGestureScope(
// 点击事件
onTap = { offset ->
},
// 双击事件
onDoubleTap = { offset ->
},
// 长按事件
onLongPress = { offset ->
}
)
) { }
```
## 🥭 ZoomableViewState
在`ZoomableView`中展示的内容有一个最大缩放率,可以通过`maxScale`来设置,进行放大、缩小超过极值时会有一个恢复的过程动画,可以配置一个`animationSpec`来修改这个动画的规格
```kotlin
// 获取一张图片
val painter = painterResource(id = R.drawable.light_02)
// 创建一个ZoomableViewState
val state = rememberZoomableState(
contentSize = painter.intrinsicSize,
// 设置组件最大缩放率
maxScale = 4F,
// 设置组件进行动画时的动画规格
animationSpec = tween(1200)
)
```
通过`ZoomableViewState`可以获取`ZoomableView`的各种状态参数:
```kotlin
state.isRunning() // 获取组件是否在动画状态
state.displaySize // 获取组件1倍显示的大小
state.scale // 获取组件当前相对于1倍显示大小的缩放率
state.offsetX // 获取组件的X轴位移
state.offsetY // 获取组件的Y轴位移
state.rotation // 获取组件旋转角度
```
通过`ZoomableViewState`控制`ZoomableView`的缩放率在最大值、最小值间切换:
```kotlin
val scope = rememberCoroutineScope()
ZoomableView(
state = state,
detectGesture = ZoomableGestureScope(
onDoubleTap = { offset ->
scope.launch {
// 在最大和最小显示倍率间切换,如果当前缩放率即不是最大值,
// 也不是最小值,会恢复到默认显示大小
state.toggleScale(offset)
}
},
onLongPress = { _ ->
// 恢复到默认显示大小
scope.launch { state.reset() }
}
)
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
)
}
```
================================================
FILE: doc/mkdocs.yml
================================================
# Project information
site_name: Scale
site_description: An image viewer for jetpack compose
site_author: 2022 jvziyaoyao
site_url: https://jvziyaoyao.github.io/scale/
remote_branch: gh-pages
# Configuration
theme:
name: material
language: zh
favicon: 'image/scale_icon.svg'
logo: 'image/scale_icon.svg'
palette:
# Palette toggle for automatic mode
- media: "(prefers-color-scheme)"
toggle:
icon: material/brightness-auto
name: Switch to light mode
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
primary: white
accent: white
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: black
accent: black
toggle:
icon: material/brightness-4
name: Switch to light mode
font:
text: 'Roboto'
code: 'Roboto Mono'
# Repository
repo_name: Scale
repo_url: https://github.com/jvziyaoyao/scale
# Copyright
copyright: Copyright © 2022 jvziyaoyao
# Customization
extra:
social:
- icon: fontawesome/brands/github
link: https://github.com/jvziyaoyao/scale
- icon: fontawesome/solid/mug-hot
link: https://www.jvziyaoyao.com
nav:
- Overview: index.md
- Getting Started: getting_started.md
- ImageViewer: image_viewer.md
- ImagePager: image_pager.md
- ImagePreviewer: image_previewer.md
- SamplingDecoder: sampling_decoder.md
- ZoomableView: zoomable_view.md
- ZoomablePager: zoomable_pager.md
- Previewer: previewer.md
- Reference ⏏: reference/index.html
- Change Log: change_log.md
================================================
FILE: doc/run_doc_server.sh
================================================
# 启动文档服务
python3 -m mkdocs serve
================================================
FILE: gradle/libs.versions.toml
================================================
[versions]
bignum = "0.3.10"
compose-compiler = "1.5.0"
compose = "1.9.3"
coil = "3.0.0-rc01"
accompanist = "0.34.0"
android-gradle-plugin = "8.10.1"
core-ktx = "1.16.0"
junit = "4.13.2"
androidx-test-ext-junit = "1.2.1"
espresso-core = "3.6.1"
appcompat = "1.7.0"
material = "1.12.0"
material-icons = "1.7.8"
kotlin = "2.2.21"
kotlinStdlib = "2.2.21"
kotlinTest = "2.1.0"
runner = "1.5.2"
core = "1.7.0"
compose-plugin = "1.8.1"
kotlin-datetime = "0.7.1"
ktor = "3.0.0"
maven-publish = "0.32.0"
skiko = "0.9.4.2"
dokka = "1.9.20"
kotlinx-coroutines = "1.10.2"
scale = "1.1.1-beta.3"
[libraries]
androidx-exif = "androidx.exifinterface:exifinterface:1.4.0"
androidx-lifecycle-runtime = "androidx.lifecycle:lifecycle-runtime-ktx:2.8.7"
androidx-activity-compose = "androidx.activity:activity-compose:1.9.0"
androidx-constraintlayout-compose = "androidx.constraintlayout:constraintlayout-compose:1.1.1"
androidx-navigation-compose = "androidx.navigation:navigation-compose:2.8.9"
bignum = { module = "com.ionspin.kotlin:bignum", version.ref = "bignum" }
jvziyaoyao-origeek-ui = "com.github.jvziyaoyao:OrigeekUI:1.0.1-alpha.7"
androidx-compose-ui-util = { group = "androidx.compose.ui", name = "ui-util", version.ref = "compose" }
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui", version.ref = "compose" }
androidx-compose-material = { group = "androidx.compose.material", name = "material", version.ref = "compose" }
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview", version.ref = "compose" }
androidx-compose-ui-test = { group = "androidx.compose.ui", name = "ui-test-junit4", version.ref = "compose" }
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "compose" }
androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended", version.ref = "material-icons" }
coil = { group = "io.coil-kt", name = "coil", version.ref = "coil" }
coil-gif = { group = "io.coil-kt", name = "coil-gif", version.ref = "coil" }
#coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coil" }
coil-compose = { module = "io.coil-kt.coil3:coil-compose", version.ref = "coil" }
coil-network-ktor3 = { module = "io.coil-kt.coil3:coil-network-ktor3", version.ref = "coil" }
coil-svg = { module = "io.coil-kt.coil3:coil-svg", version.ref = "coil" }
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "ktor" }
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
kotlinx-coroutines-swing = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-swing", version.ref = "kotlinx-coroutines" }
google-accompanist-permissions = { group = "com.google.accompanist", name = "accompanist-permissions", version.ref = "accompanist" }
google-accompanist-systemuicontroller = { group = "com.google.accompanist", name = "accompanist-systemuicontroller", version.ref = "accompanist" }
core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "core-ktx" }
junit-junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-test-ext-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidx-test-ext-junit" }
espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espresso-core" }
appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
skiko = { module = "org.jetbrains.skiko:skiko", version.ref = "skiko" }
scale-image-viewer = { group = "com.jvziyaoyao.scale", name = "image-viewer", version.ref = "scale" }
scale-image-viewer-classic = { group = "com.jvziyaoyao.scale", name = "image-viewer-classic", version.ref = "scale" }
scale-sampling-decoder = { group = "com.jvziyaoyao.scale", name = "sampling-decoder", version.ref = "scale" }
kotlin-stdlib = { group = "org.jetbrains.kotlin", name = "kotlin-stdlib", version.ref = "kotlinStdlib" }
kotlin-test = { group = "org.jetbrains.kotlin", name = "kotlin-test", version.ref = "kotlinTest" }
androidx-runner = { group = "androidx.test", name = "runner", version.ref = "runner" }
androidx-core = { group = "androidx.test", name = "core", version.ref = "core" }
org-jetbrains-kotlinx-datetime = { group = "org.jetbrains.kotlinx", name = "kotlinx-datetime", version.ref = "kotlin-datetime" }
gradle-plugin-android = { module = "com.android.tools.build:gradle", version.ref = "android-gradle-plugin" }
gradle-plugin-jetbrains-compose = { module = "org.jetbrains.compose:compose-gradle-plugin", version.ref = "compose" }
gradle-plugin-compose-compiler = { module = "org.jetbrains.kotlin.plugin.compose:org.jetbrains.kotlin.plugin.compose.gradle.plugin", version.ref = "kotlin" }
gradle-plugin-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
gradle-plugin-maven-publish = { module = "com.vanniktech:gradle-maven-publish-plugin", version.ref = "maven-publish" }
gradle-plugin-dokka = { module = "org.jetbrains.dokka:dokka-gradle-plugin", version.ref = "dokka" }
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Mon Jun 20 14:14:51 CST 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
================================================
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.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# 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
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
# run sdk with module or remote aar
isApplyModule=true
#android.defaults.buildfeatures.buildconfig=true
android.nonFinalResIds=false
# Config
minSdk=24
targetSdk=35
compileSdk=35
# Maven
#
#GROUP=com.jvziyaoyao.scaler
#VERSION_NAME=1.1.1-alpha.10
GROUP=com.jvziyaoyao.scale
VERSION_NAME=1.1.1-beta.3
RELEASE_SIGNING_ENABLED=true
SONATYPE_HOST=CENTRAL_PORTAL
#
POM_DESCRIPTION=An image viewer for jetpack compose.
POM_INCEPTION_YEAR=2022
POM_URL=https://github.com/jvziyaoyao/scale
#
POM_SCM_URL=https://github.com/jvziyaoyao/scale
POM_SCM_CONNECTION=https://github.com/jvziyaoyao/scale.git
POM_SCM_DEV_CONNECTION=https://github.com/jvziyaoyao/scale.git
#
POM_LICENCE_NAME=The Apache License, Version 2.0
POM_LICENCE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt
POM_LICENCE_DIST=repo
#
POM_DEVELOPER_ID=jvziyaoyao
POM_DEVELOPER_NAME=jvziyaoyao
POM_DEVELOPER_URL=https://github.com/jvziyaoyao
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# 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
#
# https://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.
#
##############################################################################
##
## 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='"-Xmx64m" "-Xms64m"'
# 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 or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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=`expr $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"
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@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 Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@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="-Xmx64m" "-Xms64m"
@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 execute
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 execute
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
: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 %*
: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: sample-android/.gitignore
================================================
/build
================================================
FILE: sample-android/build.gradle.kts
================================================
import scale.compileSdk
import scale.minSdk
import scale.targetSdk
plugins {
id("org.jetbrains.kotlin.plugin.compose")
id("com.android.application")
id("org.jetbrains.compose")
id("kotlin-android")
}
val kmpResDir = "composeResources/scale.sample_kmp.generated.resources"
tasks.register("copySharedResources") {
from(project(":sample-kmp").file("src/commonMain/composeResources"))
into(layout.buildDirectory.dir("generated/kmpCopy/$kmpResDir"))
}
android {
namespace = "com.jvziyaoyao.scale.sample"
compileSdk = project.compileSdk
defaultConfig {
applicationId = "com.jvziyaoyao.scale.sample"
minSdk = project.minSdk
targetSdk = project.targetSdk
versionCode = 1
versionName = "1.1.0-alpha.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}
buildTypes {
release {
isMinifyEnabled = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = libs.versions.compose.compiler.get()
}
// packagingOptions {
// resources {
// excludes += "/META-INF/{AL2.0,LGPL2.1}"
// }
// }
sourceSets.getByName("main") {
assets.srcDirs(
"src/main/assets",
layout.buildDirectory.dir("generated/kmpCopy"),
)
}
// composeResources/scale.sample_kmp.generated.resources/files/a350.jpg
applicationVariants.all {
this.mergeAssetsProvider.configure {
dependsOn("copySharedResources")
}
}
}
dependencies {
implementation(project(":scale-image-viewer-classic"))
implementation(project(":scale-image-viewer"))
implementation(project(":scale-sampling-decoder"))
// implementation(project(":scale-sampling-decoder-kmp"))
implementation(project(":scale-zoomable-view"))
implementation(project(":sample-kmp"))
// implementation(libs.scale.image.viewer)
// implementation(libs.scale.image.viewer.classic)
// implementation(libs.scale.sampling.decoder)
implementation(libs.androidx.exif)
implementation(compose.components.resources)
implementation(libs.androidx.navigation.compose)
implementation(libs.jvziyaoyao.origeek.ui)
// implementation(libs.coil)
implementation(libs.coil.svg)
// implementation(libs.coil.gif)
implementation(libs.coil.compose)
implementation(libs.google.accompanist.permissions)
implementation(libs.google.accompanist.systemuicontroller)
implementation(libs.androidx.constraintlayout.compose)
implementation(libs.core.ktx)
implementation(libs.appcompat)
implementation(libs.material)
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.material)
implementation(libs.androidx.compose.ui.tooling.preview)
debugImplementation(libs.androidx.compose.ui.tooling)
implementation(libs.androidx.compose.ui.util)
androidTestImplementation(libs.androidx.compose.ui.test)
implementation(libs.androidx.compose.material.icons.extended)
implementation(libs.androidx.lifecycle.runtime)
implementation(libs.androidx.activity.compose)
testImplementation(libs.junit.junit)
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.espresso.core)
}
================================================
FILE: sample-android/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.kts.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
================================================
FILE: sample-android/src/androidTest/java/com/jvziyaoyao/image/viewer/ExampleInstrumentedTest.kt
================================================
package com.jvziyaoyao.image.viewer
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.origeek.imageviewer", appContext.packageName)
}
}
================================================
FILE: sample-android/src/main/AndroidManifest.xml
================================================
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/base/BaseActivity.kt
================================================
package com.jvziyaoyao.scale.sample.base
import android.content.res.Configuration
import androidx.activity.ComponentActivity
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.Composable
import com.jvziyaoyao.scale.sample.ui.theme.ScaleSampleTheme
import com.jvziyaoyao.scale.sample.ui.theme.ViewerDemoTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
open class BaseActivity : ComponentActivity(), CoroutineScope by MainScope() {
fun setBasicContent(
content: @Composable () -> Unit,
) {
val systemBarStyle =
when (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
Configuration.UI_MODE_NIGHT_NO -> SystemBarStyle.light(
android.graphics.Color.TRANSPARENT,
android.graphics.Color.TRANSPARENT
)
Configuration.UI_MODE_NIGHT_YES -> SystemBarStyle.dark(android.graphics.Color.TRANSPARENT)
else -> SystemBarStyle.light(
android.graphics.Color.TRANSPARENT,
android.graphics.Color.TRANSPARENT
)
}
enableEdgeToEdge(
statusBarStyle = systemBarStyle,
navigationBarStyle = systemBarStyle,
)
setContent {
ScaleSampleTheme {
content()
}
}
}
override fun onDestroy() {
cancel()
super.onDestroy()
}
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/base/BasePermission.kt
================================================
package com.jvziyaoyao.scale.sample.base
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
/**
* @program: TestFocusable
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2024-01-23 20:55
**/
fun Context.openSetting() {
val intent = Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", packageName, null)
)
startActivity(intent)
}
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun CommonPermissions(
permissions: List,
onPermissionChange: (Boolean) -> Unit,
content: @Composable () -> Unit
) {
val permissionState =
rememberMultiplePermissionsState(
permissions = permissions,
)
LaunchedEffect(key1 = permissionState.allPermissionsGranted, block = {
onPermissionChange(permissionState.allPermissionsGranted)
})
if (permissionState.allPermissionsGranted) {
content()
} else {
val context = LocalContext.current
CommonPermissionNotGranted(
launchPermissionRequest = {
permissionState.launchMultiplePermissionRequest()
},
goSetting = {
context.openSetting()
}
)
}
}
@Composable
fun CommonPermissionNotGranted(
label: String = "👋 我们需要获取权限才能使用该功能~",
launchPermissionRequest: () -> Unit,
goSetting: () -> Unit,
) {
Column(Modifier.fillMaxSize()) {
Spacer(modifier = Modifier.statusBarsPadding())
Column(
modifier = Modifier
.fillMaxWidth()
.weight(1F)
.padding(bottom = 32.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = label)
Spacer(modifier = Modifier.height(24.dp))
Button(onClick = {
launchPermissionRequest()
}) {
Text(text = "🛸 授予权限", color = MaterialTheme.colors.surface)
}
Spacer(modifier = Modifier.height(60.dp))
Text(
text = "如果无法授予权限,请通过下方按钮前往设置~",
color = LocalContentColor.current.copy(0.8F)
)
Spacer(modifier = Modifier.height(18.dp))
Text(text = "👇")
Spacer(modifier = Modifier.height(18.dp))
Button(
onClick = {
goSetting()
},
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colors.background
)
) {
Text(text = "🚑 前往设置", color = MaterialTheme.colors.primary)
}
}
}
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/DecoderActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.os.Bundle
import com.jvziyaoyao.scale.sample.base.BaseActivity
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-10-05 14:31
**/
class DecoderActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setBasicContent {
DecoderBody()
}
}
}
//@Composable
//fun DecoderBody() {
// BoxWithConstraints(
// modifier = Modifier
// .fillMaxSize(),
// ) {
// val key = "2887"
// val context = LocalContext.current
// val scope = rememberCoroutineScope()
// val previewerState = rememberPreviewerState(
// verticalDragType = VerticalDragType.Down,
// pageCount = { 1 },
// getKey = { key },
// )
// val inputStream = remember { context.assets.open("a350.jpg") }
// val painter = painterResource(R.drawable.a350_temp)
// val itemState = rememberTransformItemState(
// intrinsicSize = painter.intrinsicSize,
// )
// val horizontal = this@BoxWithConstraints.maxWidth > maxHeight
// // Save
// var transformEnable by rememberSaveable { mutableStateOf(true) }
// var loadDelay by rememberSaveable { mutableStateOf(0F) }
// var rotation by rememberSaveable { mutableStateOf(0F) }
// if (previewerState.canClose || previewerState.animating) BackHandler {
// if (previewerState.canClose) scope.launch {
// if (transformEnable) {
// previewerState.exitTransform()
// } else {
// previewerState.close()
// }
// }
// }
// Column(
// modifier = Modifier
// .fillMaxSize(),
// horizontalAlignment = Alignment.CenterHorizontally,
// verticalArrangement = Arrangement.Center,
// ) {
// Box(
// Modifier.size(120.dp), contentAlignment = Alignment.Center
// ) {
// ScaleGrid(
// detectGesture = DetectScaleGridGesture(
// onPress = {
// scope.launch {
// if (transformEnable) {
// previewerState.enterTransform(0)
// } else {
// previewerState.open(0)
// }
// }
// }
// )
// ) {
// TransformItemView(
// key = key,
// itemState = itemState,
// transformState = previewerState,
// ) {
// Image(
// modifier = Modifier.fillMaxSize(),
// painter = painter,
// contentScale = ContentScale.Crop,
// contentDescription = null,
// )
// }
// }
// }
// Spacer(modifier = Modifier.height(if (horizontal) 12.dp else 24.dp))
// Text(text = "👆 Clickable")
// Spacer(modifier = Modifier.height(if (horizontal) 24.dp else 72.dp))
// Column(modifier = Modifier.fillMaxWidth(if (horizontal) 0.4F else 0.6F)) {
// Row(
// modifier = Modifier.fillMaxWidth(),
// verticalAlignment = Alignment.CenterVertically,
// horizontalArrangement = Arrangement.SpaceBetween,
// ) {
// Text(text = "Transform:")
// Switch(
// checked = transformEnable,
// onCheckedChange = {
// transformEnable = it
// },
// colors = SwitchDefaults.colors(
// checkedThumbColor = MaterialTheme.colors.primary
// )
// )
// }
// Spacer(modifier = Modifier.height(if (horizontal) 10.dp else 20.dp))
// Row(
// modifier = Modifier.fillMaxWidth(),
// verticalAlignment = Alignment.CenterVertically,
// horizontalArrangement = Arrangement.SpaceBetween,
// ) {
// Text(text = "Delay ${loadDelay.toLong()}:")
// Slider(
// modifier = Modifier
// .height(48.dp)
// .width(100.dp),
// value = loadDelay,
// valueRange = 0F..4000F,
// onValueChange = {
// loadDelay = it
// },
// )
// }
// Spacer(modifier = Modifier.height(if (horizontal) 10.dp else 20.dp))
// Row(
// modifier = Modifier.fillMaxWidth(),
// verticalAlignment = Alignment.CenterVertically,
// horizontalArrangement = Arrangement.SpaceBetween,
// ) {
// Text(text = "Rotation ${ceil(rotation).toInt()}:")
// Slider(
// modifier = Modifier
// .height(48.dp)
// .width(100.dp),
// value = rotation,
// valueRange = 0F..270F,
// steps = 2,
// onValueChange = {
// rotation = it
// },
// )
// }
// }
// }
//
// ImagePreviewer(
// state = previewerState,
// processor = ModelProcessor(samplingProcessorPair),
// imageLoader = { _ ->
// val decoderRotation = when (rotation.toInt()) {
// SamplingDecoder.Rotation.ROTATION_90.radius -> SamplingDecoder.Rotation.ROTATION_90
// SamplingDecoder.Rotation.ROTATION_180.radius -> SamplingDecoder.Rotation.ROTATION_180
// SamplingDecoder.Rotation.ROTATION_270.radius -> SamplingDecoder.Rotation.ROTATION_270
// else -> SamplingDecoder.Rotation.ROTATION_0
// }
// val (samplingDecoder, error) = rememberSamplingDecoder(
// inputStream = inputStream,
// rotation = decoderRotation
// )
// val realSamplingDecoder = remember { mutableStateOf(null) }
// LaunchedEffect(samplingDecoder) {
// if (samplingDecoder != null) {
// delay(loadDelay.toLong())
// realSamplingDecoder.value = samplingDecoder
// }
// }
// return@ImagePreviewer Pair(
// realSamplingDecoder.value,
// realSamplingDecoder.value?.intrinsicSize
// )
// }
// )
// }
//}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/DuplicateActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.os.Bundle
import com.jvziyaoyao.scale.sample.base.BaseActivity
class DuplicateActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setBasicContent {
DuplicateBody()
}
}
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/GalleryActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.os.Bundle
import com.jvziyaoyao.scale.sample.base.BaseActivity
class GalleryActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setBasicContent {
GalleryBody()
// GalleryBody01()
// GalleryBody02()
}
}
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/HomeActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.content.Intent
import android.os.Bundle
import com.jvziyaoyao.scale.sample.base.BaseActivity
class HomeActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setBasicContent {
HomeBody(
onZoomable = {
val intent = Intent(this, ZoomableActivity::class.java)
startActivity(intent)
},
onNormal = {
val intent = Intent(this, NormalActivity::class.java)
startActivity(intent)
},
onHuge = {
val intent = Intent(this, HugeActivity::class.java)
startActivity(intent)
},
onGallery = {
val intent = Intent(this, GalleryActivity::class.java)
startActivity(intent)
},
onPreviewer = {
val intent = Intent(this, PreviewerActivity::class.java)
startActivity(intent)
},
onTransform = {
val intent = Intent(this, TransformActivity::class.java)
startActivity(intent)
},
onDecoder = {
val intent = Intent(this, DecoderActivity::class.java)
startActivity(intent)
},
onDuplicate = {
val intent = Intent(this, DuplicateActivity::class.java)
startActivity(intent)
},
)
}
}
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/HugeActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.os.Bundle
import com.jvziyaoyao.scale.sample.base.BaseActivity
class HugeActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setBasicContent {
HugeBody()
// HugeBody01()
}
}
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/NormalActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.os.Bundle
import com.jvziyaoyao.scale.sample.base.BaseActivity
class NormalActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setBasicContent {
NormalBody()
}
}
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/PicturesActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.Manifest
import android.os.Build
import android.os.Bundle
import android.os.Environment
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material.Icon
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Error
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.graphics.drawable.toBitmap
import com.jvziyaoyao.scale.image.previewer.ImagePreviewer
import com.jvziyaoyao.scale.image.sampling.SamplingDecoder
import com.jvziyaoyao.scale.image.sampling.createSamplingDecoder
import com.jvziyaoyao.scale.image.sampling.samplingProcessorPair
import com.jvziyaoyao.scale.image.viewer.AnyComposable
import com.jvziyaoyao.scale.image.viewer.ModelProcessor
import com.jvziyaoyao.scale.sample.base.BaseActivity
import com.jvziyaoyao.scale.sample.base.CommonPermissions
import com.jvziyaoyao.scale.zoomable.previewer.PreviewerState
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemView
import com.jvziyaoyao.scale.zoomable.previewer.rememberPreviewerState
import com.jvziyaoyao.scale.zoomable.previewer.rememberTransformItemState
import com.origeek.ui.common.compose.DetectScaleGridGesture
import com.origeek.ui.common.compose.ScaleGrid
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
val requirePermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
listOf(
Manifest.permission.READ_MEDIA_IMAGES,
Manifest.permission.READ_MEDIA_AUDIO,
Manifest.permission.READ_MEDIA_VIDEO,
)
} else {
listOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
)
}
class PicturesActivity : BaseActivity() {
private val imagesFileList = mutableStateListOf()
// TODO 这里需要换一个更通用的路径
private fun getStoragePath(): File {
val picturesFile =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absoluteFile
val storageFile = File(picturesFile, "yao")
if (!storageFile.exists()) storageFile.mkdirs()
return storageFile
}
private fun fetchImages() {
val yaoDirectory = getStoragePath()
val fileList = yaoDirectory.listFiles()
?.filter { it.isFile }
// ?.filter { it.length() > 0 }
?.toList()?.reversed() ?: emptyList()
imagesFileList.clear()
imagesFileList.addAll(fileList)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setBasicContent {
CommonPermissions(
permissions = requirePermissions,
onPermissionChange = {
if (it) launch(Dispatchers.IO) {
fetchImages()
}
}
) {
// PicturesBody(
// images = imagesFileList,
// )
}
}
}
}
//@Composable
//fun PicturesBody(
// images: List,
//) {
// Box(modifier = Modifier.fillMaxSize()) {
// val previewerState = rememberPreviewerState(
// pageCount = { images.size },
// getKey = { images[it].absolutePath },
// )
// PicturesGridLayer(
// images = images,
// previewerState = previewerState,
// )
// PicturesDecoderPreviewLayer(
// images = images,
// previewerState = previewerState,
// )
// }
//}
//
//@Composable
//fun PicturesDecoderPreviewLayer(
// images: List,
// previewerState: PreviewerState,
//) {
// val context = LocalContext.current
// val scope = rememberCoroutineScope()
// ImagePreviewer(
// state = previewerState,
// debugMode = true,
// processor = ModelProcessor(samplingProcessorPair),
// imageLoader = { page ->
// val file = images[page]
// val pair = remember { mutableStateOf>(Pair(null, null)) }
// LaunchedEffect(Unit) {
// scope.launch(Dispatchers.IO) {
// try {
// createSamplingDecoder(file)?.let {
// pair.value = Pair(it, it.intrinsicSize)
// }
// } catch (e: Exception) {
// e.printStackTrace()
// }
// if (pair.value.first != null) return@launch
// loadPainter(context, file)?.let {
// val painter = BitmapPainter(it.toBitmap().asImageBitmap())
// pair.value = Pair(painter, painter.intrinsicSize)
// }
// if (pair.value.first != null) return@launch
// pair.value = Pair(AnyComposable {
// ErrorPlaceHolder()
// }, null)
// }
// }
// DisposableEffect(Unit) {
// onDispose {
// if (pair.value.first is SamplingDecoder) {
// (pair.value.first as SamplingDecoder).release()
// }
// }
// }
// pair.value
// },
// )
//
//}
//
//@Composable
//fun ErrorPlaceHolder() {
// Column(
// modifier = Modifier
// .fillMaxSize(),
// horizontalAlignment = Alignment.CenterHorizontally,
// verticalArrangement = Arrangement.Center,
// ) {
// val color = Color.White.copy(0.4F)
// Icon(
// modifier = Modifier
// .size(40.dp),
// imageVector = Icons.Filled.Error,
// tint = color,
// contentDescription = null
// )
// Spacer(modifier = Modifier.height(12.dp))
// Text(text = "图片加载失败", color = color)
// }
//}
//
//@Composable
//fun PicturesGridLayer(
// images: List,
// previewerState: PreviewerState,
//) {
// val scope = rememberCoroutineScope()
// val lineCount = 4
// LazyVerticalGrid(
// modifier = Modifier.statusBarsPadding(),
// columns = GridCells.Fixed(lineCount)
// ) {
// images.forEachIndexed { index, item ->
// item(key = item.absolutePath) {
// val needStart = index % lineCount != 0
// Box(
// modifier = Modifier
// .fillMaxWidth()
// .aspectRatio(1F)
// .padding(start = if (needStart) 2.dp else 0.dp, bottom = 2.dp),
// contentAlignment = Alignment.Center
// ) {
// ScaleGrid(
// detectGesture = DetectScaleGridGesture(
// onPress = {
// scope.launch {
// previewerState.enterTransform(index)
// }
// }
// )
// ) {
// val painter = rememberAsyncImagePainter(item)
// val itemState =
// rememberTransformItemState(
// intrinsicSize = painter.intrinsicSize
// )
// TransformItemView(
// modifier = Modifier
// .background(MaterialTheme.colors.background),
// key = item.absolutePath,
// itemState = itemState,
// transformState = previewerState,
// ) {
// Box(
// modifier = Modifier
// .fillMaxSize()
// ) {
// Image(
// modifier = Modifier.fillMaxSize(),
// painter = painter,
// contentScale = ContentScale.Crop,
// contentDescription = null,
// )
// if (painter.state is AsyncImagePainter.State.Error) {
// Icon(
// modifier = Modifier
// .size(30.dp)
// .align(Alignment.Center),
// imageVector = Icons.Filled.Error,
// tint = LocalContentColor.current.copy(0.04F),
// contentDescription = null
// )
// }
// }
// }
// }
// }
// }
// }
// }
//}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/PreviewerActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.os.Bundle
import com.jvziyaoyao.scale.sample.base.BaseActivity
import com.origeek.ui.common.util.hideSystemUI
import com.origeek.ui.common.util.showSystemUI
const val SYSTEM_UI_VISIBILITY = "SYSTEM_UI_VISIBILITY"
class PreviewerActivity : BaseActivity() {
private var systemUIVisible = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handlerSystemUI(savedInstanceState?.getBoolean(SYSTEM_UI_VISIBILITY) ?: true)
setBasicContent {
PreviewerBody {
if (systemUIVisible != !it) {
handlerSystemUI(!it)
}
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putBoolean(SYSTEM_UI_VISIBILITY, systemUIVisible)
super.onSaveInstanceState(outState)
}
private fun handlerSystemUI(visible: Boolean) {
systemUIVisible = visible
if (systemUIVisible) {
showSystemUI(window)
} else {
hideSystemUI(window)
}
}
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/TransformActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.os.Bundle
import com.jvziyaoyao.scale.sample.base.BaseActivity
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-09-21 18:20
**/
class TransformActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setBasicContent {
TransformBody()
}
}
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/page/ZoomableActivity.kt
================================================
package com.jvziyaoyao.scale.sample.page
import android.os.Bundle
import com.jvziyaoyao.scale.sample.base.BaseActivity
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-11-24 16:24
**/
class ZoomableActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setBasicContent {
ZoomableBody()
}
}
}
//@Composable
//fun ZoomableBody() {
// val scope = rememberCoroutineScope()
//
// val url = "https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF"
// val painter = rememberCoilImagePainter(url)
// val zoomableState = rememberZoomableState(contentSize = painter.intrinsicSize)
//
// Box(
// modifier = Modifier
// .fillMaxSize()
// .padding(40.dp)
// ) {
// zoomableState.apply {
// ZoomableView(
// modifier = Modifier
// .fillMaxSize()
// .background(Color.Blue.copy(0.2F)),
// state = zoomableState,
// boundClip = false,
// detectGesture = ZoomableGestureScope(
// onTap = {
//
// },
// onDoubleTap = {
// scope.launch {
// zoomableState.toggleScale(it)
// }
// },
// onLongPress = {
//
// },
// ),
// ) {
// Image(
// modifier = Modifier.fillMaxSize(),
// painter = painter,
// contentDescription = null,
// )
// }
// Box(
// modifier = Modifier
// .graphicsLayer {
// translationX = gestureCenter.value.x - 6.dp.toPx()
// translationY = gestureCenter.value.y - 6.dp.toPx()
// }
// .clip(CircleShape)
// .background(Color.Red.copy(0.4f))
// .size(12.dp)
// )
// Box(
// modifier = Modifier
// .clip(CircleShape)
// .background(Color.Cyan)
// .size(12.dp)
// .align(Alignment.Center)
// )
// }
// Box(
// modifier = Modifier
// .fillMaxSize()
// .background(Color.Yellow.copy(0.2F))
// )
// }
//}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/ui/component/ImageLoader.kt
================================================
package com.jvziyaoyao.scale.sample.ui.component
//import android.content.Context
//import android.graphics.BitmapRegionDecoder
//import android.graphics.drawable.Drawable
//import android.os.Build
//import androidx.compose.runtime.Composable
//import androidx.compose.runtime.DisposableEffect
//import androidx.compose.runtime.LaunchedEffect
//import androidx.compose.runtime.getValue
//import androidx.compose.runtime.mutableStateOf
//import androidx.compose.runtime.remember
//import androidx.compose.runtime.setValue
//import androidx.compose.ui.graphics.painter.Painter
//import androidx.compose.ui.platform.LocalContext
//import coil.compose.rememberAsyncImagePainter
//import coil.imageLoader
//import coil.request.ImageRequest
//import com.jvziyaoyao.scale.image.sampling.SamplingDecoder
//import kotlinx.coroutines.Dispatchers
//import kotlinx.coroutines.delay
//import kotlinx.coroutines.launch
//import java.io.InputStream
//import kotlin.coroutines.resume
//import kotlin.coroutines.suspendCoroutine
//
//@Composable
//fun rememberCoilImagePainter(image: Any): Painter {
// // 加载图片
// val imageRequest = ImageRequest.Builder(LocalContext.current)
// .data(image)
// .size(coil.size.Size.ORIGINAL)
// .build()
// // 获取图片的初始大小
// return rememberAsyncImagePainter(imageRequest)
//}
//
//suspend fun loadPainter(context: Context, data: Any) = suspendCoroutine { c ->
// val imageRequest = ImageRequest.Builder(context)
// .data(data)
// .size(coil.size.Size.ORIGINAL)
// .target(
// onSuccess = {
// c.resume(it)
// },
// onError = {
// c.resume(null)
// }
// )
// .build()
// context.imageLoader.enqueue(imageRequest)
//}
//
//@Composable
//fun rememberBitmapRegionDecoder(
// inputStream: InputStream,
//): BitmapRegionDecoder? {
// val decoder = remember { mutableStateOf(null) }
// LaunchedEffect(inputStream) {
// launch(Dispatchers.IO) {
// decoder.value = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// BitmapRegionDecoder.newInstance(inputStream)
// } else {
// BitmapRegionDecoder.newInstance(inputStream,false)
// }
// }
// }
// return decoder.value
//}
//
//@Composable
//fun rememberDecoderImagePainter(
// inputStream: InputStream,
// rotation: Int = 0,
// delay: Long? = null,
//): SamplingDecoder? {
// var samplingDecoder by remember { mutableStateOf(null) }
// LaunchedEffect(inputStream) {
// launch(Dispatchers.IO) {
// if (delay != null) delay(delay)
// samplingDecoder = try {
// val decoder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// BitmapRegionDecoder.newInstance(inputStream)
// } else {
// BitmapRegionDecoder.newInstance(inputStream,false)
// }
// if (decoder == null) {
// null
// } else {
// val decoderRotation = when(rotation) {
// SamplingDecoder.Rotation.ROTATION_90.radius -> SamplingDecoder.Rotation.ROTATION_90
// SamplingDecoder.Rotation.ROTATION_180.radius -> SamplingDecoder.Rotation.ROTATION_180
// SamplingDecoder.Rotation.ROTATION_270.radius -> SamplingDecoder.Rotation.ROTATION_270
// else -> SamplingDecoder.Rotation.ROTATION_0
// }
// SamplingDecoder(
// decoder = decoder,
// rotation = decoderRotation
// )
// }
// } catch (e: Exception) {
// e.printStackTrace()
// null
// }
// }
// }
// DisposableEffect(Unit) {
// onDispose {
// samplingDecoder?.release()
// }
// }
// return samplingDecoder
//}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/ui/component/Layout.kt
================================================
package com.jvziyaoyao.scale.sample.ui.component
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/ui/theme/Color.kt
================================================
package com.jvziyaoyao.scale.sample.ui.theme
import androidx.compose.ui.graphics.Color
// light
val light_f = Color(0xFFFFFFFF)
// font
val font_f = Color(0XFF111727)
// accent
val accent_f = Color(0xFF456DE6)
val accent_dark_f = Color(0xFF999999)
// second
val second_f = Color(0xFFF3F5FD)
// second
val surface = Color(0x08456DE6)
// error
val error_f = Color(0xFFAC483B)
// success
val success_f = Color(0xFFB6D7C4)
// back
val back_dark_f = Color(0xFF272727)
val pink_f = Color(0xFFF3ACC6)
val royal_f = Color(0xFFBAA3FC)
val stable_f = Color(0xFFEFEFEF)
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/ui/theme/Layout.kt
================================================
package com.jvziyaoyao.scale.sample.ui.theme
import androidx.compose.foundation.layout.BoxWithConstraintsScope
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* @program: ImageGallery
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-07-28 19:50
**/
class Padding(
val pxxs: Dp = 2.dp,
val pxs: Dp = 4.dp,
val ps: Dp = 8.dp,
val pm: Dp = 12.dp,
val pl: Dp = 20.dp,
val pxl: Dp = 36.dp,
val pxxl: Dp = 48.dp,
)
class FontSize(
val fxxs: TextUnit = 10.sp,
val fxs: TextUnit = 12.sp,
val fs: TextUnit = 14.sp,
val fm: TextUnit = 16.sp,
val fl: TextUnit = 18.sp,
val fxl: TextUnit = 24.sp,
val fxxl: TextUnit = 28.sp,
val fh: TextUnit = 32.sp,
)
class RoundShape(
val rs_dp: Dp = 6.dp,
val rm_dp: Dp = 12.dp,
val rl_dp: Dp = 18.dp,
val rxl_dp: Dp = 28.dp,
val rs: RoundedCornerShape = RoundedCornerShape(rs_dp),
val rm: RoundedCornerShape = RoundedCornerShape(rm_dp),
val rl: RoundedCornerShape = RoundedCornerShape(rl_dp),
val rxl: RoundedCornerShape = RoundedCornerShape(rxl_dp),
)
object Layout {
private val defaultPadding = Padding()
private val defaultFontSize = FontSize()
private val defaultRoundShape = RoundShape()
val padding: Padding
@Composable
get() = defaultPadding
val fontSize: FontSize
@Composable
get() = defaultFontSize
val roundShape: RoundShape
@Composable
get() = defaultRoundShape
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/ui/theme/Shape.kt
================================================
package com.jvziyaoyao.scale.sample.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
)
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/ui/theme/Theme.kt
================================================
package com.jvziyaoyao.scale.sample.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
val DarkColorPalette = darkColors(
primary = accent_dark_f,
secondary = second_f.copy(0.1f),
background = back_dark_f,
surface = light_f.copy(0.08f),
onPrimary = light_f.copy(0.8f),
onSecondary = font_f.copy(0.8f),
onBackground = light_f.copy(0.72f),
onSurface = font_f.copy(0.8f),
error = error_f,
)
val LightColorPalette = lightColors(
primary = accent_f,
secondary = stable_f.copy(0.6f),
background = stable_f,
surface = light_f,
onPrimary = light_f.copy(0.8f),
onSecondary = font_f.copy(0.8f),
onBackground = font_f.copy(0.8f),
onSurface = font_f.copy(0.8f),
error = error_f,
)
@Composable
fun ViewerDemoTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable() () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
================================================
FILE: sample-android/src/main/java/com/jvziyaoyao/scale/sample/ui/theme/Type.kt
================================================
package com.jvziyaoyao.scale.sample.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
)
================================================
FILE: sample-android/src/main/res/drawable/ic_dark_bg.xml
================================================
================================================
FILE: sample-android/src/main/res/drawable/ic_empty_image.xml
================================================
================================================
FILE: sample-android/src/main/res/drawable/ic_launcher_foreground.xml
================================================
================================================
FILE: sample-android/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
================================================
================================================
FILE: sample-android/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
================================================
================================================
FILE: sample-android/src/main/res/values/colors.xml
================================================
#00FFFFFF
#FF000000
#FFFFFFFF
#CCFFFFFF
#99FFFFFF
#00FFFFFF
#33FFFFFF
#FF111727
#99111727
#33111727
#CC111727
#FF414552
#FF456DE6
#CC456DE6
#FF0043B3
#FF000018
#FF819BFF
#FFAAB6CB
#FF7B869A
#FFDCE8FE
#FFAC483B
#FFFFD9A0
#FFB6D7C4
#FFF3ACC6
#FFBAA3FC
#FFEFEFEF
#CCEFEFEF
================================================
FILE: sample-android/src/main/res/values/ic_launcher_background.xml
================================================
#FFFFFF
================================================
FILE: sample-android/src/main/res/values/strings.xml
================================================
ImageViewer
================================================
FILE: sample-android/src/main/res/values/themes.xml
================================================
================================================
FILE: sample-android/src/main/res/values-night/themes.xml
================================================
================================================
FILE: sample-android/src/main/res/values-v27/themes.xml
================================================
================================================
FILE: sample-android/src/main/res/xml/network_security_config.xml
================================================
================================================
FILE: sample-android/src/test/java/com/jvziyaoyao/image/viewer/ExampleUnitTest.kt
================================================
package com.jvziyaoyao.image.viewer
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
================================================
FILE: sample-ios/iosSample/Assets.xcassets/AccentColor.colorset/Contents.json
================================================
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
================================================
FILE: sample-ios/iosSample/Assets.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"images" : [
{
"filename" : "appIcon.jpg",
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "tinted"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
================================================
FILE: sample-ios/iosSample/Assets.xcassets/Contents.json
================================================
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
================================================
FILE: sample-ios/iosSample/ContentView.swift
================================================
//
// ContentView.swift
// iosSample
//
// Created by 橘子妖妖 on 2025/6/27.
//
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
}
}
#Preview {
ContentView()
}
================================================
FILE: sample-ios/iosSample/Preview Content/Preview Assets.xcassets/Contents.json
================================================
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
================================================
FILE: sample-ios/iosSample/component/ComposeView.swift
================================================
//
// ComposeView.swift
// iosSample
//
// Created by 橘子妖妖 on 2025/6/27.
//
import UIKit
import SwiftUI
import SampleKmpKit
struct ComposeView: UIViewControllerRepresentable {
var getViewController: () -> UIViewController
func makeUIViewController(context: Context) -> UIViewController {
return getViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
struct NavigationStackGestureEnabler: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> UIViewController {
let vc = UIViewController()
DispatchQueue.main.async {
if let navigationController = vc.navigationController {
navigationController.interactivePopGestureRecognizer?.delegate = nil
navigationController.interactivePopGestureRecognizer?.isEnabled = true
}
}
return vc
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
struct ComposeSwiperView: View {
let content: () -> Content
let barWidth: CGFloat
let needSwiper: Bool
init(barWidth: CGFloat = 20, needSwiper: Bool = true, @ViewBuilder content: @escaping () -> Content) {
self.content = content
self.barWidth = barWidth
self.needSwiper = needSwiper
}
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
content()
if needSwiper {
Rectangle()
.foregroundColor(.white)
.opacity(0.012)
.frame(width: barWidth, height: geometry.size.height)
.contentShape(Rectangle())
.allowsHitTesting(true)
}
}
.ignoresSafeArea(.all, edges: .all)
.toolbar(.hidden)
.background(NavigationStackGestureEnabler())
}
}
}
================================================
FILE: sample-ios/iosSample/iosSampleApp.swift
================================================
//
// iosSampleApp.swift
// iosSample
//
// Created by 橘子妖妖 on 2025/6/27.
//
import SwiftUI
@main
struct iosSampleApp: App {
var body: some Scene {
WindowGroup {
NavigationPageView {
HomePageView()
}
}
}
}
================================================
FILE: sample-ios/iosSample/page/HomeViewController.swift
================================================
//
// HomeViewController.swift
// iosSample
//
// Created by 橘子妖妖 on 2025/6/28.
//
import SwiftUI
import SampleKmpKit
struct HomePageView: View {
@EnvironmentObject var navigationManager: NavigationManager
var body: some View {
ComposeSwiperView {
ComposeView {
return ViewControllerKt.homeViewController(
onZoomable: {
navigationManager.next(page: .Zoomable)
},
onNormal: {
navigationManager.next(page: .Normal)
},
onHuge: {
navigationManager.next(page: .Huge)
},
onGallery: {
navigationManager.next(page: .Gallery)
},
onPreviewer: {
navigationManager.next(page: .Previewer)
},
onTransform: {
navigationManager.next(page: .Transform)
},
onDecoder: {
navigationManager.next(page: .Decoder)
},
onDuplicate: {
navigationManager.next(page: .Duplicate)
}
)
}
}
}
}
struct ZoomablePageView: View {
@EnvironmentObject var navigationManager: NavigationManager
var body: some View {
ComposeSwiperView {
ComposeView {
return ViewControllerKt.zoomableViewController()
}
}
}
}
struct NormalPageView: View {
@EnvironmentObject var navigationManager: NavigationManager
var body: some View {
ComposeSwiperView {
ComposeView {
return ViewControllerKt.normalViewController()
}
}
}
}
struct HugePageView: View {
@EnvironmentObject var navigationManager: NavigationManager
var body: some View {
ComposeSwiperView {
ComposeView {
return ViewControllerKt.hugeViewController()
}
}
}
}
struct GalleryPageView: View {
@EnvironmentObject var navigationManager: NavigationManager
var body: some View {
ComposeSwiperView {
ComposeView {
return ViewControllerKt.galleryViewController()
}
}
}
}
struct PreviewerPageView: View {
@EnvironmentObject var navigationManager: NavigationManager
var body: some View {
ComposeSwiperView {
ComposeView {
return ViewControllerKt.previewerViewController()
}
}
}
}
struct TransformPageView: View {
@EnvironmentObject var navigationManager: NavigationManager
var body: some View {
ComposeSwiperView {
ComposeView {
return ViewControllerKt.transformViewController()
}
}
}
}
struct DecoderPageView: View {
@EnvironmentObject var navigationManager: NavigationManager
var body: some View {
ComposeSwiperView {
ComposeView {
return ViewControllerKt.decoderViewController()
}
}
}
}
struct DuplicatePageView: View {
@EnvironmentObject var navigationManager: NavigationManager
var body: some View {
ComposeSwiperView {
ComposeView {
return ViewControllerKt.duplicateViewController()
}
}
}
}
================================================
FILE: sample-ios/iosSample/page/NavigationPageView.swift
================================================
//
// NavigationPageView.swift
// iosSample
//
// Created by 橘子妖妖 on 2025/6/28.
//
import SampleKmpKit
import SwiftUI
class NavigationManager: ObservableObject {
@Published var path = NavigationPath()
func next(page: Page) {
path.append(page)
}
func back() {
DispatchQueue.main.async {
if self.path.count > 0 {
self.path.removeLast()
}
}
}
func goHome() {
while path.count > 0 {
path.removeLast(path.count)
}
}
}
struct NavigationPageView: View {
@StateObject private var navigationManager = NavigationManager()
var content: () -> Content
var body: some View {
NavigationStack(path: $navigationManager.path) {
ZStack {
self.content()
}
.navigationDestination(for: Page.self) { target in
target.view
}
}
.environmentObject(navigationManager)
.ignoresSafeArea(.all, edges: .all)
.toolbar(.hidden)
}
}
enum Page: Hashable {
case Home
case Zoomable
case Normal
case Huge
case Gallery
case Previewer
case Transform
case Decoder
case Duplicate
@ViewBuilder
var view: some View {
switch self {
case .Home:
HomePageView()
case .Zoomable:
ZoomablePageView()
case .Normal:
NormalPageView()
case .Huge:
HugePageView()
case .Gallery:
GalleryPageView()
case .Previewer:
PreviewerPageView()
case .Transform:
TransformPageView()
case .Decoder:
DecoderPageView()
case .Duplicate:
DuplicatePageView()
}
}
}
struct NotFoundPageView: View {
var body: some View {
Text("页面找不到~")
}
}
struct RoomTestPage: View {
var body: some View {
Text("好家伙")
}
}
================================================
FILE: sample-ios/iosSample.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 77;
objects = {
/* Begin PBXContainerItemProxy section */
C8086DFF2E0EE62D00D32B13 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = C8086DE62E0EE62C00D32B13 /* Project object */;
proxyType = 1;
remoteGlobalIDString = C8086DED2E0EE62C00D32B13;
remoteInfo = iosSample;
};
C8086E092E0EE62D00D32B13 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = C8086DE62E0EE62C00D32B13 /* Project object */;
proxyType = 1;
remoteGlobalIDString = C8086DED2E0EE62C00D32B13;
remoteInfo = iosSample;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
C8086DEE2E0EE62C00D32B13 /* iosSample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iosSample.app; sourceTree = BUILT_PRODUCTS_DIR; };
C8086DFE2E0EE62D00D32B13 /* iosSampleTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = iosSampleTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
C8086E082E0EE62D00D32B13 /* iosSampleUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = iosSampleUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
C8086DF02E0EE62C00D32B13 /* iosSample */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = iosSample;
sourceTree = "";
};
C8086E012E0EE62D00D32B13 /* iosSampleTests */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = iosSampleTests;
sourceTree = "";
};
C8086E0B2E0EE62D00D32B13 /* iosSampleUITests */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = iosSampleUITests;
sourceTree = "";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
C8086DEB2E0EE62C00D32B13 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C8086DFB2E0EE62D00D32B13 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C8086E052E0EE62D00D32B13 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
C8086DE52E0EE62C00D32B13 = {
isa = PBXGroup;
children = (
C8086DF02E0EE62C00D32B13 /* iosSample */,
C8086E012E0EE62D00D32B13 /* iosSampleTests */,
C8086E0B2E0EE62D00D32B13 /* iosSampleUITests */,
C8086DEF2E0EE62C00D32B13 /* Products */,
);
sourceTree = "";
};
C8086DEF2E0EE62C00D32B13 /* Products */ = {
isa = PBXGroup;
children = (
C8086DEE2E0EE62C00D32B13 /* iosSample.app */,
C8086DFE2E0EE62D00D32B13 /* iosSampleTests.xctest */,
C8086E082E0EE62D00D32B13 /* iosSampleUITests.xctest */,
);
name = Products;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
C8086DED2E0EE62C00D32B13 /* iosSample */ = {
isa = PBXNativeTarget;
buildConfigurationList = C8086E122E0EE62D00D32B13 /* Build configuration list for PBXNativeTarget "iosSample" */;
buildPhases = (
C8086E2A2E0EE73900D32B13 /* Run Script */,
C8086DEA2E0EE62C00D32B13 /* Sources */,
C8086DEB2E0EE62C00D32B13 /* Frameworks */,
C8086DEC2E0EE62C00D32B13 /* Resources */,
);
buildRules = (
);
dependencies = (
);
fileSystemSynchronizedGroups = (
C8086DF02E0EE62C00D32B13 /* iosSample */,
);
name = iosSample;
packageProductDependencies = (
);
productName = iosSample;
productReference = C8086DEE2E0EE62C00D32B13 /* iosSample.app */;
productType = "com.apple.product-type.application";
};
C8086DFD2E0EE62D00D32B13 /* iosSampleTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = C8086E152E0EE62D00D32B13 /* Build configuration list for PBXNativeTarget "iosSampleTests" */;
buildPhases = (
C8086DFA2E0EE62D00D32B13 /* Sources */,
C8086DFB2E0EE62D00D32B13 /* Frameworks */,
C8086DFC2E0EE62D00D32B13 /* Resources */,
);
buildRules = (
);
dependencies = (
C8086E002E0EE62D00D32B13 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
C8086E012E0EE62D00D32B13 /* iosSampleTests */,
);
name = iosSampleTests;
packageProductDependencies = (
);
productName = iosSampleTests;
productReference = C8086DFE2E0EE62D00D32B13 /* iosSampleTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
C8086E072E0EE62D00D32B13 /* iosSampleUITests */ = {
isa = PBXNativeTarget;
buildConfigurationList = C8086E182E0EE62D00D32B13 /* Build configuration list for PBXNativeTarget "iosSampleUITests" */;
buildPhases = (
C8086E042E0EE62D00D32B13 /* Sources */,
C8086E052E0EE62D00D32B13 /* Frameworks */,
C8086E062E0EE62D00D32B13 /* Resources */,
);
buildRules = (
);
dependencies = (
C8086E0A2E0EE62D00D32B13 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
C8086E0B2E0EE62D00D32B13 /* iosSampleUITests */,
);
name = iosSampleUITests;
packageProductDependencies = (
);
productName = iosSampleUITests;
productReference = C8086E082E0EE62D00D32B13 /* iosSampleUITests.xctest */;
productType = "com.apple.product-type.bundle.ui-testing";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C8086DE62E0EE62C00D32B13 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1600;
TargetAttributes = {
C8086DED2E0EE62C00D32B13 = {
CreatedOnToolsVersion = 16.0;
};
C8086DFD2E0EE62D00D32B13 = {
CreatedOnToolsVersion = 16.0;
TestTargetID = C8086DED2E0EE62C00D32B13;
};
C8086E072E0EE62D00D32B13 = {
CreatedOnToolsVersion = 16.0;
TestTargetID = C8086DED2E0EE62C00D32B13;
};
};
};
buildConfigurationList = C8086DE92E0EE62C00D32B13 /* Build configuration list for PBXProject "iosSample" */;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = C8086DE52E0EE62C00D32B13;
minimizedProjectReferenceProxies = 1;
preferredProjectObjectVersion = 77;
productRefGroup = C8086DEF2E0EE62C00D32B13 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
C8086DED2E0EE62C00D32B13 /* iosSample */,
C8086DFD2E0EE62D00D32B13 /* iosSampleTests */,
C8086E072E0EE62D00D32B13 /* iosSampleUITests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
C8086DEC2E0EE62C00D32B13 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C8086DFC2E0EE62D00D32B13 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C8086E062E0EE62D00D32B13 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
C8086E2A2E0EE73900D32B13 /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = "Run Script";
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = "/bin/sh\n./gradlew :shared:embedAndSignAppleFrameworkForXcode";
shellScript = "cd \"$SRCROOT/..\"\n./gradlew :sample-kmp:embedAndSignAppleFrameworkForXcode\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
C8086DEA2E0EE62C00D32B13 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C8086DFA2E0EE62D00D32B13 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
C8086E042E0EE62D00D32B13 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
C8086E002E0EE62D00D32B13 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = C8086DED2E0EE62C00D32B13 /* iosSample */;
targetProxy = C8086DFF2E0EE62D00D32B13 /* PBXContainerItemProxy */;
};
C8086E0A2E0EE62D00D32B13 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = C8086DED2E0EE62C00D32B13 /* iosSample */;
targetProxy = C8086E092E0EE62D00D32B13 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
C8086E102E0EE62D00D32B13 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
C8086E112E0EE62D00D32B13 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
C8086E132E0EE62D00D32B13 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"iosSample/Preview Content\"";
DEVELOPMENT_TEAM = JC73H96SXY;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.jvziyaoyao.scale.iosSample;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
C8086E142E0EE62D00D32B13 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"iosSample/Preview Content\"";
DEVELOPMENT_TEAM = JC73H96SXY;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.jvziyaoyao.scale.iosSample;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
C8086E162E0EE62D00D32B13 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = JC73H96SXY;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.jvziyaoyao.scale.iosSampleTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/iosSample.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/iosSample";
};
name = Debug;
};
C8086E172E0EE62D00D32B13 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = JC73H96SXY;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.jvziyaoyao.scale.iosSampleTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/iosSample.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/iosSample";
};
name = Release;
};
C8086E192E0EE62D00D32B13 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = JC73H96SXY;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.jvziyaoyao.scale.iosSampleUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = iosSample;
};
name = Debug;
};
C8086E1A2E0EE62D00D32B13 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = JC73H96SXY;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.jvziyaoyao.scale.iosSampleUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = iosSample;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C8086DE92E0EE62C00D32B13 /* Build configuration list for PBXProject "iosSample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C8086E102E0EE62D00D32B13 /* Debug */,
C8086E112E0EE62D00D32B13 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C8086E122E0EE62D00D32B13 /* Build configuration list for PBXNativeTarget "iosSample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C8086E132E0EE62D00D32B13 /* Debug */,
C8086E142E0EE62D00D32B13 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C8086E152E0EE62D00D32B13 /* Build configuration list for PBXNativeTarget "iosSampleTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C8086E162E0EE62D00D32B13 /* Debug */,
C8086E172E0EE62D00D32B13 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C8086E182E0EE62D00D32B13 /* Build configuration list for PBXNativeTarget "iosSampleUITests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C8086E192E0EE62D00D32B13 /* Debug */,
C8086E1A2E0EE62D00D32B13 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = C8086DE62E0EE62C00D32B13 /* Project object */;
}
================================================
FILE: sample-ios/iosSample.xcodeproj/project.xcworkspace/contents.xcworkspacedata
================================================
================================================
FILE: sample-ios/iosSample.xcodeproj/project.xcworkspace/xcuserdata/jvziyaoyao.xcuserdatad/xcschemes/xcschememanagement.plist
================================================
================================================
FILE: sample-ios/iosSample.xcodeproj/xcuserdata/jvziyaoyao.xcuserdatad/xcschemes/iosSample.xcscheme
================================================
================================================
FILE: sample-ios/iosSample.xcodeproj/xcuserdata/jvziyaoyao.xcuserdatad/xcschemes/xcschememanagement.plist
================================================
SchemeUserState
iosSample.xcscheme
orderHint
0
================================================
FILE: sample-ios/iosSampleTests/iosSampleTests.swift
================================================
//
// iosSampleTests.swift
// iosSampleTests
//
// Created by 橘子妖妖 on 2025/6/27.
//
import Testing
@testable import iosSample
struct iosSampleTests {
@Test func example() async throws {
// Write your test here and use APIs like `#expect(...)` to check expected conditions.
}
}
================================================
FILE: sample-ios/iosSampleUITests/iosSampleUITests.swift
================================================
//
// iosSampleUITests.swift
// iosSampleUITests
//
// Created by 橘子妖妖 on 2025/6/27.
//
import XCTest
final class iosSampleUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
@MainActor
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
@MainActor
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
================================================
FILE: sample-ios/iosSampleUITests/iosSampleUITestsLaunchTests.swift
================================================
//
// iosSampleUITestsLaunchTests.swift
// iosSampleUITests
//
// Created by 橘子妖妖 on 2025/6/27.
//
import XCTest
final class iosSampleUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
@MainActor
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
================================================
FILE: sample-kmp/.gitignore
================================================
/build
================================================
FILE: sample-kmp/build.gradle.kts
================================================
import scale.compileSdk
import scale.minSdk
plugins {
id("com.android.kotlin.multiplatform.library")
id("org.jetbrains.kotlin.plugin.compose")
id("org.jetbrains.kotlin.multiplatform")
id("org.jetbrains.compose")
}
kotlin {
androidLibrary {
namespace = "com.jvziyaoyao.scale.sample"
compileSdk = project.compileSdk
minSdk = project.minSdk
}
jvm()
listOf(
iosX64(),
iosArm64(),
iosSimulatorArm64()
).forEach { iosTarget ->
iosTarget.binaries.framework {
baseName = "SampleKmpKit"
isStatic = true
}
}
sourceSets {
commonMain {
dependencies {
implementation(project(":scale-image-viewer"))
implementation(project(":scale-zoomable-view"))
implementation(project(":scale-sampling-decoder"))
implementation(compose.materialIconsExtended)
implementation(compose.material)
implementation(compose.material3)
implementation(libs.coil.compose)
implementation(libs.coil.network.ktor3)
implementation(libs.kotlin.stdlib)
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.ui)
api(compose.components.resources)
implementation(compose.components.uiToolingPreview)
implementation(libs.org.jetbrains.kotlinx.datetime)
}
}
commonTest {
dependencies {
implementation(libs.kotlin.test)
}
}
androidMain {
dependencies {
implementation(libs.androidx.activity.compose)
// Ktor
implementation(libs.ktor.client.okhttp)
}
}
iosMain {
dependencies {
implementation(libs.ktor.client.darwin)
}
}
}
}
//compose.desktop {
// application {
// mainClass = "com.jvziyaoyao.scale.sampe.MainKt"
//
// nativeDistributions {
// targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
// packageName = "com.jvziyaoyao.scale.sampe"
// packageVersion = "1.0.1"
// }
// }
//}
================================================
FILE: sample-kmp/src/androidMain/AndroidManifest.xml
================================================
================================================
FILE: sample-kmp/src/androidMain/kotlin/com/jvziyaoyao/scale/sample/base/BaseMathod.android.kt
================================================
package com.jvziyaoyao.scale.sample.base
import android.util.Log
import androidx.compose.runtime.Composable
@Composable
actual fun BackHandler(enabled: Boolean, onBack: () -> Unit) {
androidx.activity.compose.BackHandler(enabled) {
onBack.invoke()
}
}
actual fun log(msg: String, tag: String) {
Log.i(tag, msg)
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/base/BaseMathod.kt
================================================
package com.jvziyaoyao.scale.sample.base
import androidx.compose.runtime.Composable
@Composable
expect fun BackHandler(enabled: Boolean = true, onBack: () -> Unit)
expect fun log(
msg: String,
tag: String = "ScaleDefaultTag",
)
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/page/Decoder.kt
================================================
package com.jvziyaoyao.scale.sample.page
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.Slider
import androidx.compose.material.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.jvziyaoyao.scale.image.previewer.ImagePreviewer
import com.jvziyaoyao.scale.image.sampling.SamplingDecoder
import com.jvziyaoyao.scale.image.sampling.rememberSamplingDecoder
import com.jvziyaoyao.scale.image.sampling.samplingProcessorPair
import com.jvziyaoyao.scale.image.viewer.ModelProcessor
import com.jvziyaoyao.scale.sample.base.BackHandler
import com.jvziyaoyao.scale.sample.ui.component.DetectScaleGridGesture
import com.jvziyaoyao.scale.sample.ui.component.ScaleGrid
import com.jvziyaoyao.scale.sample.ui.theme.getSlideColors
import com.jvziyaoyao.scale.sample.ui.theme.getSwitchColors
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemView
import com.jvziyaoyao.scale.zoomable.previewer.VerticalDragType
import com.jvziyaoyao.scale.zoomable.previewer.rememberPreviewerState
import com.jvziyaoyao.scale.zoomable.previewer.rememberTransformItemState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import scale.sample_kmp.generated.resources.Res
import kotlin.math.ceil
import kotlin.math.roundToInt
@Composable
fun DecoderBody() {
BoxWithConstraints(
modifier = Modifier
.fillMaxSize(),
) {
val key = "2887"
val scope = rememberCoroutineScope()
val previewerState = rememberPreviewerState(
verticalDragType = VerticalDragType.Down,
pageCount = { 1 },
getKey = { key },
)
val horizontal = this@BoxWithConstraints.maxWidth > maxHeight
// Save
var transformEnable by rememberSaveable { mutableStateOf(true) }
var loadDelay by rememberSaveable { mutableStateOf(0F) }
var rotation by rememberSaveable { mutableStateOf(0F) }
if (previewerState.canClose || previewerState.animating) BackHandler {
if (previewerState.canClose) scope.launch {
if (transformEnable) {
previewerState.exitTransform()
} else {
previewerState.close()
}
}
}
val bytes = remember { mutableStateOf(null) }
LaunchedEffect(Unit) {
bytes.value = Res.readBytes("files/a350.jpg")
}
val realRotation = roundToNearest90(rotation)
val decoderRotation = when (realRotation) {
SamplingDecoder.Rotation.ROTATION_90.radius -> SamplingDecoder.Rotation.ROTATION_90
SamplingDecoder.Rotation.ROTATION_180.radius -> SamplingDecoder.Rotation.ROTATION_180
SamplingDecoder.Rotation.ROTATION_270.radius -> SamplingDecoder.Rotation.ROTATION_270
else -> SamplingDecoder.Rotation.ROTATION_0
}
val (samplingDecoder, error) = rememberSamplingDecoder(
bytes = bytes.value,
rotation = decoderRotation
)
val imageBitmap = remember { mutableStateOf(null) }
val itemState = rememberTransformItemState(
intrinsicSize = imageBitmap.value?.let {
Size(it.width.toFloat(), it.height.toFloat())
},
)
LaunchedEffect(samplingDecoder) {
if (samplingDecoder != null) {
imageBitmap.value = samplingDecoder.createTempBitmap()
}
}
Column(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Box(
Modifier.size(120.dp), contentAlignment = Alignment.Center
) {
ScaleGrid(
detectGesture = DetectScaleGridGesture(
onPress = {
scope.launch {
if (transformEnable) {
previewerState.enterTransform(0)
} else {
previewerState.open(0)
}
}
}
)
) {
TransformItemView(
key = key,
itemState = itemState,
transformState = previewerState,
) {
imageBitmap.value?.let {
Image(
modifier = Modifier.fillMaxSize(),
bitmap = it,
contentScale = ContentScale.Crop,
contentDescription = null,
)
}
}
}
}
Spacer(modifier = Modifier.height(if (horizontal) 12.dp else 24.dp))
Text(text = "👆 Clickable")
Spacer(modifier = Modifier.height(if (horizontal) 24.dp else 72.dp))
Column(modifier = Modifier.fillMaxWidth(if (horizontal) 0.4F else 0.6F)) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(text = "Transform:")
Switch(
checked = transformEnable,
onCheckedChange = {
transformEnable = it
},
colors = getSwitchColors(),
)
}
Spacer(modifier = Modifier.height(if (horizontal) 10.dp else 20.dp))
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(text = "Delay ${loadDelay.toLong()}:")
Slider(
modifier = Modifier
.height(48.dp)
.width(100.dp),
colors = getSlideColors(),
value = loadDelay,
valueRange = 0F..4000F,
onValueChange = {
loadDelay = it
},
)
}
Spacer(modifier = Modifier.height(if (horizontal) 10.dp else 20.dp))
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(text = "Rotation ${ceil(rotation).toInt()}:")
Slider(
modifier = Modifier
.height(48.dp)
.width(100.dp),
colors = getSlideColors(),
value = rotation,
valueRange = 0F..270F,
steps = 2,
onValueChange = {
rotation = it
},
)
}
}
}
ImagePreviewer(
state = previewerState,
processor = ModelProcessor(samplingProcessorPair),
imageLoader = { _ ->
val realSamplingDecoder = remember { mutableStateOf(null) }
LaunchedEffect(samplingDecoder) {
if (samplingDecoder != null) {
delay(loadDelay.toLong())
realSamplingDecoder.value = samplingDecoder
}
}
return@ImagePreviewer Pair(
realSamplingDecoder.value,
realSamplingDecoder.value?.intrinsicSize
)
}
)
}
}
fun roundToNearest90(rotation: Float): Int {
val normalized = rotation % 360f
val rounded = (normalized / 90f).roundToInt() * 90
return (rounded % 360 + 360) % 360 // 确保结果在 0..359
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/page/Duplicate.kt
================================================
package com.jvziyaoyao.scale.sample.page
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.jvziyaoyao.scale.image.previewer.ImagePreviewer
import com.jvziyaoyao.scale.sample.base.BackHandler
import com.jvziyaoyao.scale.sample.ui.component.DetectScaleGridGesture
import com.jvziyaoyao.scale.sample.ui.component.ScaleGrid
import com.jvziyaoyao.scale.zoomable.previewer.PreviewerState
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemState
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemView
import com.jvziyaoyao.scale.zoomable.previewer.VerticalDragType
import com.jvziyaoyao.scale.zoomable.previewer.rememberPreviewerState
import com.jvziyaoyao.scale.zoomable.previewer.rememberTransformItemState
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.painterResource
import scale.sample_kmp.generated.resources.Res
import scale.sample_kmp.generated.resources.img_03
import scale.sample_kmp.generated.resources.img_06
@Composable
fun DuplicateBody() {
val scope = rememberCoroutineScope()
val imageIds = remember { listOf(Res.drawable.img_03, Res.drawable.img_06) }
val itemStateMap01 = remember { mutableStateMapOf() }
val previewerState01 = rememberPreviewerState(
verticalDragType = VerticalDragType.UpAndDown,
transformItemStateMap = itemStateMap01,
pageCount = { imageIds.size },
getKey = { imageIds[it] },
)
if (previewerState01.canClose || previewerState01.animating) BackHandler {
if (previewerState01.canClose) scope.launch {
previewerState01.exitTransform()
}
}
val itemStateMap02 = remember { mutableStateMapOf() }
val previewerState02 = rememberPreviewerState(
verticalDragType = VerticalDragType.UpAndDown,
transformItemStateMap = itemStateMap02,
pageCount = { imageIds.size },
getKey = { imageIds[it] },
)
if (previewerState02.canClose || previewerState02.animating) BackHandler {
if (previewerState02.canClose) scope.launch {
previewerState02.exitTransform()
}
}
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
DuplicateRow(
imageIds = imageIds,
previewerState = previewerState01,
)
Spacer(modifier = Modifier.height(20.dp))
DuplicateRow(
imageIds = imageIds,
previewerState = previewerState02,
)
}
ImagePreviewer(
state = previewerState01,
imageLoader = { index ->
val painter = painterResource(imageIds[index])
return@ImagePreviewer Pair(painter, painter.intrinsicSize)
}
)
ImagePreviewer(
state = previewerState02,
imageLoader = { index ->
val painter = painterResource(imageIds[index])
return@ImagePreviewer Pair(painter, painter.intrinsicSize)
}
)
}
@Composable
fun DuplicateRow(
imageIds: List,
previewerState: PreviewerState,
) {
val scope = rememberCoroutineScope()
Row {
imageIds.forEachIndexed { index, drawable ->
val painter = painterResource(drawable)
val itemState =
rememberTransformItemState(
intrinsicSize = painter.intrinsicSize
)
Box(
modifier = Modifier
.size(120.dp)
.padding(2.dp)
) {
ScaleGrid(
detectGesture = DetectScaleGridGesture(
onPress = {
scope.launch {
previewerState.enterTransform(index)
}
}
)
) {
TransformItemView(
key = drawable,
itemState = itemState,
transformState = previewerState,
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentScale = ContentScale.Crop,
contentDescription = null,
)
}
}
}
}
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/page/Gallery.kt
================================================
package com.jvziyaoyao.scale.sample.page
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.jvziyaoyao.scale.image.pager.ImagePager
import com.jvziyaoyao.scale.sample.ui.component.rememberCoilImagePainter
import com.jvziyaoyao.scale.zoomable.pager.ZoomablePager
import com.jvziyaoyao.scale.zoomable.pager.rememberZoomablePagerState
import org.jetbrains.compose.resources.painterResource
import scale.sample_kmp.generated.resources.Res
import scale.sample_kmp.generated.resources.light_01
import scale.sample_kmp.generated.resources.light_02
import scale.sample_kmp.generated.resources.light_03
@Composable
fun GalleryBody() {
// val images = remember {
// mutableStateListOf(
// "https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
// "https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
// "https://t7.baidu.com/it/u=1423490396,3473826719&fm=193&f=GIF",
// "https://t7.baidu.com/it/u=938052523,709452322&fm=193&f=GIF",
// )
// }
val images = remember {
mutableStateListOf(
Res.drawable.light_01,
Res.drawable.light_02,
Res.drawable.light_03,
)
}
// ImagePager(
// modifier = Modifier.fillMaxSize(),
// pagerState = rememberZoomablePagerState { images.size },
// imageLoader = { index ->
// val painter = rememberCoilImagePainter(image = images[index])
// val pair = remember { mutableStateOf>(Pair(null, null)) }
// LaunchedEffect(painter) {
// delay(1000)
// pair.value = Pair(painter, painter.intrinsicSize)
// }
// return@ImagePager pair.value
// },
// )
ImagePager(
modifier = Modifier.fillMaxSize(),
pagerState = rememberZoomablePagerState { images.size },
imageLoader = { index ->
val painter = painterResource(images[index])
return@ImagePager Pair(painter, painter.intrinsicSize)
},
)
}
@Composable
fun GalleryBody01() {
val images = remember {
mutableStateListOf(
Res.drawable.light_01,
Res.drawable.light_02,
Res.drawable.light_03,
)
}
val galleryState =
rememberZoomablePagerState { images.size }
ZoomablePager(state = galleryState) { page ->
val image = images[page]
val painter = rememberCoilImagePainter(image)
Box(
modifier = Modifier
.fillMaxSize()
.background(
if (page % 2 == 0)
Color.Red.copy(0.2F) else Color.Blue.copy(0.2F)
)
) {
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
)
}
}
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/page/Home.kt
================================================
package com.jvziyaoyao.scale.sample.page
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.jvziyaoyao.scale.sample.ui.theme.Layout
enum class HomeAction() {
Zoomable,
Normal,
Huge,
Gallery,
Previewer,
Transform,
Decoder,
// Pictures,
Duplicate,
}
@Composable
fun HomeBody(
onZoomable: () -> Unit,
onNormal: () -> Unit,
onHuge: () -> Unit,
onGallery: () -> Unit,
onPreviewer: () -> Unit,
onTransform: () -> Unit,
onDecoder: () -> Unit,
onDuplicate: () -> Unit,
) {
val state = rememberScrollState()
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
.verticalScroll(state = state)
.systemBarsPadding()
.padding(Layout.padding.pl),
verticalArrangement = Arrangement.spacedBy(24.dp),
) {
HomeAction.entries.forEach { action ->
HomeLargeButton(
title = action.name,
onClick = {
when (action) {
HomeAction.Zoomable -> onZoomable()
HomeAction.Normal -> onNormal()
HomeAction.Huge -> onHuge()
HomeAction.Gallery -> onGallery()
HomeAction.Previewer -> onPreviewer()
HomeAction.Transform -> onTransform()
HomeAction.Decoder -> onDecoder()
HomeAction.Duplicate -> onDuplicate()
else -> {}
}
},
)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HomeLargeButton(
title: String,
onDoubleClick: () -> Unit = {},
onClick: () -> Unit,
) {
Text(
text = title,
modifier = Modifier
.clip(MaterialTheme.shapes.medium)
.combinedClickable(onClick = {
onClick()
}, onDoubleClick = {
onDoubleClick()
})
.background(MaterialTheme.colorScheme.surface)
.fillMaxWidth()
.padding(vertical = 24.dp),
textAlign = TextAlign.Center
)
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/page/Huge.kt
================================================
package com.jvziyaoyao.scale.sample.page
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import com.jvziyaoyao.scale.image.sampling.SamplingCanvas
import com.jvziyaoyao.scale.image.sampling.getViewPort
import com.jvziyaoyao.scale.image.sampling.rememberSamplingDecoder
import com.jvziyaoyao.scale.image.sampling.samplingProcessorPair
import com.jvziyaoyao.scale.image.viewer.ImageViewer
import com.jvziyaoyao.scale.image.viewer.ModelProcessor
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableGestureScope
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableView
import com.jvziyaoyao.scale.zoomable.zoomable.rememberZoomableState
import kotlinx.coroutines.launch
import scale.sample_kmp.generated.resources.Res
@Composable
fun HugeBody() {
val scope = rememberCoroutineScope()
val bytes = remember { mutableStateOf(null) }
LaunchedEffect(Unit) {
bytes.value = Res.readBytes("files/a350.jpg")
}
val (samplingDecoder) = rememberSamplingDecoder(bytes = bytes.value)
if (samplingDecoder != null) {
val state = rememberZoomableState(contentSize = samplingDecoder.intrinsicSize)
ImageViewer(
model = samplingDecoder,
state = state,
processor = ModelProcessor(samplingProcessorPair),
detectGesture = ZoomableGestureScope(
onDoubleTap = {
scope.launch {
state.toggleScale(it)
}
}
)
)
} else {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
}
@Composable
fun HugeBody01() {
val scope = rememberCoroutineScope()
val bytes = remember { mutableStateOf(null) }
LaunchedEffect(Unit) {
bytes.value = Res.readBytes("files/a350.jpg")
}
val (samplingDecoder) = rememberSamplingDecoder(bytes = bytes.value)
val zoomableState = rememberZoomableState(
contentSize = if (samplingDecoder == null) Size.Zero else Size(
width = samplingDecoder.decoderWidth.toFloat(),
height = samplingDecoder.decoderHeight.toFloat()
)
)
ZoomableView(
modifier = Modifier
.fillMaxSize(),
state = zoomableState,
boundClip = false,
detectGesture = ZoomableGestureScope(
onDoubleTap = {
scope.launch {
zoomableState.toggleScale(it)
}
},
),
) {
if (samplingDecoder != null) {
val viewPort = zoomableState.getViewPort()
SamplingCanvas(
samplingDecoder = samplingDecoder,
viewPort = viewPort,
)
}
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/page/Normal.kt
================================================
package com.jvziyaoyao.scale.sample.page
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import com.jvziyaoyao.scale.image.viewer.ImageViewer
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableGestureScope
import com.jvziyaoyao.scale.zoomable.zoomable.rememberZoomableState
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.painterResource
import scale.sample_kmp.generated.resources.Res
import scale.sample_kmp.generated.resources.light_02
@Composable
fun NormalBody() {
Box(
modifier = Modifier
.fillMaxSize()
) {
val scope = rememberCoroutineScope()
val painter = painterResource(Res.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ImageViewer(
model = painter,
state = state,
detectGesture = ZoomableGestureScope(onDoubleTap = {
scope.launch {
state.toggleScale(it)
}
})
)
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/page/Previewer.kt
================================================
package com.jvziyaoyao.scale.sample.page
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.jvziyaoyao.scale.image.previewer.ImagePreviewer
import com.jvziyaoyao.scale.sample.base.BackHandler
import com.jvziyaoyao.scale.zoomable.pager.PagerGestureScope
import com.jvziyaoyao.scale.zoomable.previewer.TransformLayerScope
import com.jvziyaoyao.scale.zoomable.previewer.rememberPreviewerState
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.painterResource
import scale.sample_kmp.generated.resources.Res
import scale.sample_kmp.generated.resources.img_01
import scale.sample_kmp.generated.resources.img_02
import scale.sample_kmp.generated.resources.img_03
import scale.sample_kmp.generated.resources.img_04
import scale.sample_kmp.generated.resources.img_05
import scale.sample_kmp.generated.resources.img_06
@Composable
fun PreviewerBody(
onImageViewVisible: (Boolean) -> Unit = {},
) {
val scope = rememberCoroutineScope()
val images = remember {
listOf(
Res.drawable.img_01,
Res.drawable.img_02,
Res.drawable.img_03,
Res.drawable.img_04,
Res.drawable.img_05,
Res.drawable.img_06,
)
}
val previewerState = rememberPreviewerState(pageCount = { images.size })
if (previewerState.visible) BackHandler {
scope.launch {
previewerState.close()
}
}
BoxWithConstraints(
modifier = Modifier
.fillMaxSize()
) {
val horizontal = this@BoxWithConstraints.maxWidth > this@BoxWithConstraints.maxHeight
val lineCount = if (horizontal) 6 else 3
Box(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 12.dp)
.padding(top = 100.dp)
) {
LazyVerticalGrid(columns = GridCells.Fixed(lineCount)) {
images.forEachIndexed { index, item ->
item {
val needStart = index % lineCount != 0
Row(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1F)
.padding(start = if (needStart) 2.dp else 0.dp, bottom = 2.dp)
) {
Image(
modifier = Modifier
.fillMaxSize()
.clickable {
scope.launch {
previewerState.open(index = index)
}
},
painter = painterResource(item),
contentDescription = null,
contentScale = ContentScale.Crop,
)
}
}
}
}
}
LaunchedEffect(key1 = previewerState.visible, block = {
onImageViewVisible(previewerState.visible)
})
ImagePreviewer(
state = previewerState,
detectGesture = PagerGestureScope(onTap = {
scope.launch {
previewerState.close()
}
}),
previewerLayer = TransformLayerScope(
background = {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(0.8F))
)
}
),
imageLoader = { index ->
val painter = painterResource(images[index])
Pair(painter, painter.intrinsicSize)
}
)
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/page/Transform.kt
================================================
package com.jvziyaoyao.scale.sample.page
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.Slider
import androidx.compose.material.Switch
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.jvziyaoyao.scale.image.previewer.ImagePreviewer
import com.jvziyaoyao.scale.sample.base.BackHandler
import com.jvziyaoyao.scale.sample.ui.component.DetectScaleGridGesture
import com.jvziyaoyao.scale.sample.ui.component.ScaleGrid
import com.jvziyaoyao.scale.sample.ui.theme.Layout
import com.jvziyaoyao.scale.sample.ui.theme.getSlideColors
import com.jvziyaoyao.scale.sample.ui.theme.getSwitchColors
import com.jvziyaoyao.scale.zoomable.pager.PagerGestureScope
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemView
import com.jvziyaoyao.scale.zoomable.previewer.VerticalDragType
import com.jvziyaoyao.scale.zoomable.previewer.rememberPreviewerState
import com.jvziyaoyao.scale.zoomable.previewer.rememberTransformItemState
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.painterResource
import scale.sample_kmp.generated.resources.Res
import scale.sample_kmp.generated.resources.img_01
import scale.sample_kmp.generated.resources.img_02
import scale.sample_kmp.generated.resources.img_03
import scale.sample_kmp.generated.resources.img_04
import scale.sample_kmp.generated.resources.img_05
import scale.sample_kmp.generated.resources.img_06
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid
data class DrawableItem(
val id: String,
val res: DrawableResource,
)
val drawableItemTempIdMap = mutableMapOf()
private val imageIds = listOf(
Res.drawable.img_01,
Res.drawable.img_02,
Res.drawable.img_03,
Res.drawable.img_04,
Res.drawable.img_05,
Res.drawable.img_06,
)
@OptIn(ExperimentalUuidApi::class)
fun getUUID(): String {
return Uuid.random().toString()
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun TransformBody() {
val images = remember { mutableStateListOf() }
fun onRepeatChanged(repeat: Int) {
images.clear()
for (i in 0 until repeat) {
for ((index, res) in imageIds.withIndex()) {
val currentIndex = i * imageIds.size + index
var id = drawableItemTempIdMap[currentIndex]
if (id == null) {
id = getUUID()
drawableItemTempIdMap[currentIndex] = id
}
images.add(
DrawableItem(
id = id,
res = res
)
)
}
}
}
fun onDeleteItem(item: DrawableItem) {
images.remove(item)
}
val settingState = remember { TransformSettingState() }
val scope = rememberCoroutineScope()
val previewerState = rememberPreviewerState(
scope = scope,
defaultAnimationSpec = tween(settingState.animationDuration),
verticalDragType = VerticalDragType.Down,
pageCount = { images.size },
getKey = { images[it].id },
)
LaunchedEffect(settingState.dataRepeat) {
onRepeatChanged(settingState.dataRepeat)
}
LaunchedEffect(images.size) {
if (images.isEmpty() && (previewerState.canClose || previewerState.animating)) {
previewerState.close()
}
}
if (previewerState.canClose || previewerState.animating) BackHandler {
if (previewerState.canClose) scope.launch {
if (settingState.transformExit) {
previewerState.exitTransform()
} else {
previewerState.close()
}
}
}
BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
val horizontal = this.maxWidth > maxHeight
val lineCount = if (horizontal) 6 else 3
Column(
modifier = Modifier
.fillMaxSize()
.systemBarsPadding()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.weight(3F),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(text = "🎈 Transform")
}
Box(
modifier = Modifier
.fillMaxWidth()
.padding(
start = Layout.padding.pxxl,
end = Layout.padding.pxxl,
bottom = Layout.padding.pxxl,
)
.weight(if (horizontal) 6F else 7F)
) {
LazyVerticalGrid(columns = GridCells.Fixed(lineCount)) {
images.forEachIndexed { index, item ->
item(key = item.id) {
val needStart = index % lineCount != 0
val painter = painterResource(item.res)
val itemState =
rememberTransformItemState(
intrinsicSize = painter.intrinsicSize
)
Box(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1F)
.animateItem()
.padding(start = if (needStart) 2.dp else 0.dp, bottom = 2.dp),
contentAlignment = Alignment.Center
) {
ScaleGrid(
detectGesture = DetectScaleGridGesture(
onPress = {
scope.launch {
if (settingState.transformEnter) {
previewerState.enterTransform(index)
} else {
previewerState.open(index)
}
}
}
)
) {
TransformItemView(
key = item.id,
itemState = itemState,
transformState = previewerState,
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentScale = ContentScale.Crop,
contentDescription = null,
)
}
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.BottomCenter
) {
Box(
modifier = Modifier
.fillMaxWidth()
.background(
MaterialTheme.colorScheme.onBackground.copy(
0.4F
)
)
.padding(vertical = Layout.padding.pxs)
.clickable {
onDeleteItem(item)
},
contentAlignment = Alignment.Center
) {
Icon(
modifier = Modifier.size(16.dp),
imageVector = Icons.Filled.Delete,
contentDescription = null,
tint = MaterialTheme.colorScheme.surface.copy(0.6F)
)
}
}
}
}
}
}
}
}
SettingSurface(settingState)
ImagePreviewer(
state = previewerState,
detectGesture = PagerGestureScope(
onTap = {
scope.launch {
previewerState.exitTransform()
}
}
),
imageLoader = { index ->
val painter = if (settingState.loaderError && (index % 2 == 0)) null
else painterResource(images[index].res)
return@ImagePreviewer Pair(painter, painter?.intrinsicSize)
}
)
}
}
@Composable
fun SettingItem(
label: String,
content: @Composable () -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = label, fontSize = 14.sp)
Box {
content()
}
}
}
@Composable
fun SettingItemSwitch(
checked: Boolean,
onCheckedChanged: (Boolean) -> Unit,
) {
Box(modifier = Modifier.padding(vertical = Layout.padding.pm)) {
Switch(
checked = checked,
onCheckedChange = onCheckedChanged,
colors = getSwitchColors()
)
}
}
val VERTICAL_DRAG_ENABLE = VerticalDragType.UpAndDown
val VERTICAL_DRAG_DISABLE = VerticalDragType.None
val DEFAULT_VERTICAL_DRAG = VERTICAL_DRAG_ENABLE
const val DEFAULT_LOADER_ERROR = false
const val DEFAULT_TRANSFORM_ENTER = true
const val DEFAULT_TRANSFORM_EXIT = true
const val DEFAULT_ANIMATION_DURATION = 400
const val DEFAULT_DATA_REPEAT = 1
class TransformSettingState {
var loaderError by mutableStateOf(DEFAULT_LOADER_ERROR)
var verticalDrag by mutableStateOf(DEFAULT_VERTICAL_DRAG)
var transformEnter by mutableStateOf(DEFAULT_TRANSFORM_ENTER)
var transformExit by mutableStateOf(DEFAULT_TRANSFORM_EXIT)
var animationDuration by mutableStateOf(DEFAULT_ANIMATION_DURATION)
var dataRepeat by mutableStateOf(DEFAULT_DATA_REPEAT)
fun reset() {
loaderError = DEFAULT_LOADER_ERROR
verticalDrag = DEFAULT_VERTICAL_DRAG
transformEnter = DEFAULT_TRANSFORM_ENTER
transformExit = DEFAULT_TRANSFORM_EXIT
animationDuration = DEFAULT_ANIMATION_DURATION
dataRepeat = DEFAULT_DATA_REPEAT
}
// companion object {
// val Saver: Saver = mapSaver(
// save = {
// mapOf(
// it::loaderError.name to it.loaderError,
// it::verticalDrag.name to it.verticalDrag,
// it::transformEnter.name to it.transformEnter,
// it::transformExit.name to it.transformExit,
// it::animationDuration.name to it.animationDuration,
// it::dataRepeat.name to it.dataRepeat,
// )
// },
// restore = {
// val state = TransformSettingState()
// state.loaderError = it[state::loaderError.name] as Boolean
// state.verticalDrag = it[state::verticalDrag.name] as VerticalDragType
// state.transformEnter = it[state::transformEnter.name] as Boolean
// state.transformExit = it[state::transformExit.name] as Boolean
// state.animationDuration = it[state::animationDuration.name] as Int
// state.dataRepeat = it[state::dataRepeat.name] as Int
// state
// }
// )
// }
}
//@Composable
//fun rememberSettingState(): TransformSettingState {
// return rememberSaveable(saver = TransformSettingState.Saver) {
// TransformSettingState()
// }
//}
@Composable
fun SettingPanel(state: TransformSettingState, onClose: () -> Unit) {
Column(modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) {
SettingPanelBanner(onClose)
Column(
modifier = Modifier
.fillMaxWidth(0.8F)
.weight(1F)
.verticalScroll(rememberScrollState())
) {
SettingItem(label = "Loader Error") {
SettingItemSwitch(checked = state.loaderError, onCheckedChanged = {
state.loaderError = it
})
}
Spacer(modifier = Modifier.height(Layout.padding.pxs))
SettingItem(label = "Vertical Drag") {
SettingItemSwitch(
checked = state.verticalDrag == VERTICAL_DRAG_ENABLE,
onCheckedChanged = {
state.verticalDrag =
if (it) VERTICAL_DRAG_ENABLE else VERTICAL_DRAG_DISABLE
})
}
Spacer(modifier = Modifier.height(Layout.padding.pxs))
SettingItem(label = "Transform Enter") {
SettingItemSwitch(checked = state.transformEnter, onCheckedChanged = {
state.transformEnter = it
})
}
Spacer(modifier = Modifier.height(Layout.padding.pxs))
SettingItem(label = "Transform Exit") {
SettingItemSwitch(checked = state.transformExit, onCheckedChanged = {
state.transformExit = it
})
}
Spacer(modifier = Modifier.height(Layout.padding.pm))
SettingItem(label = "Duration ${state.animationDuration.toLong()}") {
Slider(
modifier = Modifier
.height(48.dp)
.width(120.dp),
colors = getSlideColors(),
value = state.animationDuration.toFloat(),
valueRange = 0F..2000F,
onValueChange = {
state.animationDuration = it.toInt()
},
)
}
Spacer(modifier = Modifier.height(Layout.padding.pl))
SettingItem(label = "Data Repeat ${state.dataRepeat}") {
Slider(
modifier = Modifier
.height(48.dp)
.width(120.dp),
colors = getSlideColors(),
value = state.dataRepeat.toFloat(),
valueRange = 1F..100F,
onValueChange = {
state.dataRepeat = it.toInt()
},
)
}
Spacer(modifier = Modifier.height(Layout.padding.pxxl))
Button(
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.surface,
),
onClick = {
state.reset()
},
) {
Text(text = "Reset")
}
Spacer(modifier = Modifier.height(Layout.padding.pxxl))
}
}
}
@Composable
fun SettingPanelBanner(onClose: () -> Unit) {
Box(
modifier = Modifier.fillMaxWidth()
.height(60.dp)
) {
Box(
modifier = Modifier
.clip(CircleShape)
.clickable {
onClose()
}
.padding(Layout.padding.ps)
.align(Alignment.CenterEnd)
) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onSurface.copy(0.32F)
)
}
Text(
text = "Settings",
modifier = Modifier.align(Alignment.Center),
)
}
}
@Composable
fun SettingSurface(
settingState: TransformSettingState,
) {
var visible by rememberSaveable { mutableStateOf(false) }
if (visible) BackHandler {
visible = false
}
Box(modifier = Modifier.fillMaxSize()) {
FloatingActionButton(
onClick = {
visible = true
},
backgroundColor = MaterialTheme.colorScheme.surface,
modifier = Modifier
.padding(bottom = 100.dp, end = Layout.padding.pl)
.align(Alignment.BottomEnd)
) {
Icon(
Icons.Filled.Settings,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface.copy(0.32F)
)
}
}
Box(
modifier = Modifier
.fillMaxSize()
) {
AnimatedVisibility(
visible = visible,
modifier = Modifier.fillMaxWidth(),
enter = fadeIn(),
exit = fadeOut(),
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(0.6F))
.pointerInput(Unit) {
detectTapGestures {
visible = false
}
}
)
}
AnimatedVisibility(
visible = visible,
modifier = Modifier.fillMaxWidth(),
enter = slideInVertically { it },
exit = slideOutVertically { it },
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.BottomCenter,
) {
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.6F)
.background(MaterialTheme.colorScheme.surface)
.padding(horizontal = Layout.padding.pm)
) {
SettingPanel(settingState) {
visible = false
}
}
}
}
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/page/Zoomable.kt
================================================
package com.jvziyaoyao.scale.sample.page
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp
import com.jvziyaoyao.scale.sample.ui.component.rememberCoilImagePainter
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableGestureScope
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableView
import com.jvziyaoyao.scale.zoomable.zoomable.rememberZoomableState
import kotlinx.coroutines.launch
@Composable
fun ZoomableBody() {
val scope = rememberCoroutineScope()
val url = "https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF"
val painter = rememberCoilImagePainter(url)
val zoomableState = rememberZoomableState(contentSize = painter.intrinsicSize)
Box(
modifier = Modifier
.fillMaxSize()
.padding(40.dp)
) {
zoomableState.apply {
ZoomableView(
modifier = Modifier
.fillMaxSize()
.background(Color.Blue.copy(0.2F)),
state = zoomableState,
boundClip = false,
detectGesture = ZoomableGestureScope(
onTap = {
},
onDoubleTap = {
scope.launch {
zoomableState.toggleScale(it)
}
},
onLongPress = {
},
),
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
)
}
Box(
modifier = Modifier
.graphicsLayer {
translationX = gestureCenter.value.x - 6.dp.toPx()
translationY = gestureCenter.value.y - 6.dp.toPx()
}
.clip(CircleShape)
.background(Color.Red.copy(0.4f))
.size(12.dp)
)
Box(
modifier = Modifier
.clip(CircleShape)
.background(Color.Cyan)
.size(12.dp)
.align(Alignment.Center)
)
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Yellow.copy(0.2F))
)
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/sample/ImagePagerSample.kt
================================================
package com.jvziyaoyao.scale.sample.sample
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import coil3.compose.rememberAsyncImagePainter
import com.jvziyaoyao.scale.image.pager.ImagePager
import com.jvziyaoyao.scale.image.pager.defaultProceedPresentation
import com.jvziyaoyao.scale.zoomable.pager.rememberZoomablePagerState
import org.jetbrains.compose.resources.painterResource
import scale.sample_kmp.generated.resources.Res
import scale.sample_kmp.generated.resources.light_01
import scale.sample_kmp.generated.resources.light_02
object ImagePagerSample {
// 简单使用
@Composable
fun BasicSample() {
val images = remember {
mutableStateListOf(Res.drawable.light_01, Res.drawable.light_02)
}
val pagerState = rememberZoomablePagerState { images.size }
ImagePager(
pagerState = pagerState,
imageLoader = { page ->
val painter = painterResource(images[page])
Pair(painter, painter.intrinsicSize)
}
)
}
@Composable
fun CoilSample() {
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val pagerState = rememberZoomablePagerState { images.size }
ImagePager(
pagerState = pagerState,
imageLoader = { page ->
val painter = rememberAsyncImagePainter(model = images[page])
Pair(painter, painter.intrinsicSize)
}
)
}
@Composable
fun DecorationSample() {
val images = remember {
mutableStateListOf(Res.drawable.light_01, Res.drawable.light_02)
}
val pagerState = rememberZoomablePagerState { images.size }
ImagePager(
pagerState = pagerState,
proceedPresentation = defaultProceedPresentation,
imageLoader = { page ->
val painter = painterResource(images[page])
Pair(painter, painter.intrinsicSize)
},
imageLoading = {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center),
color = Color.Blue,
)
}
},
pageDecoration = { page, innerPage ->
Box(modifier = Modifier.background(Color.LightGray)) {
innerPage.invoke()
// 设置每一页的前景图层
Box(
modifier = Modifier
.padding(bottom = 20.dp)
.clip(RoundedCornerShape(8.dp))
.background(Color.White)
.padding(8.dp)
.align(Alignment.BottomCenter),
) {
Text(text = "${page + 1}/${images.size}")
}
}
}
)
}
@Composable
fun StateSample() {
// 参考
ZoomablePagerSample.StateSample()
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/sample/ImagePreviewerSample.kt
================================================
package com.jvziyaoyao.scale.sample.sample
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil3.compose.rememberAsyncImagePainter
import com.jvziyaoyao.scale.image.previewer.ImagePreviewer
import com.jvziyaoyao.scale.image.previewer.TransformImageView
import com.jvziyaoyao.scale.zoomable.previewer.TransformLayerScope
import com.jvziyaoyao.scale.zoomable.previewer.rememberPreviewerState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
object ImagePreviewerSample {
@Composable
fun BasicSample() {
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val state = rememberPreviewerState(pageCount = { images.size }) { images[it] }
ImagePreviewer(
state = state,
imageLoader = { page ->
val painter = rememberAsyncImagePainter(model = images[page])
Pair(painter, painter.intrinsicSize)
}
)
LaunchedEffect(Unit) {
// 展开
state.open()
// 等待四秒
delay(4 * 1000)
// 关闭
state.close()
}
}
@Composable
fun TransformSample() {
val scope = rememberCoroutineScope()
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val state = rememberPreviewerState(pageCount = { images.size }) { images[it] }
Box(modifier = Modifier.fillMaxSize()) {
Row(
modifier = Modifier.align(Alignment.Center),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
images.forEachIndexed { index, url ->
TransformImageView(
modifier = Modifier
.size(120.dp)
.clickable {
scope.launch {
state.enterTransform(index)
}
},
imageLoader = {
val painter = rememberAsyncImagePainter(model = url)
Triple(url, painter, painter.intrinsicSize)
},
transformState = state,
)
}
}
}
ImagePreviewer(
state = state,
imageLoader = { page ->
val painter = rememberAsyncImagePainter(model = images[page])
Pair(painter, painter.intrinsicSize)
}
)
}
// 编辑图层示例代码
@Composable
fun DecorationSample() {
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val state = rememberPreviewerState(pageCount = { images.size }) { images[it] }
ImagePreviewer(
state = state,
imageLoader = { page ->
val painter = rememberAsyncImagePainter(model = images[page])
Pair(painter, painter.intrinsicSize)
},
pageDecoration = { _, innerPage ->
var mounted = false
Box(modifier = Modifier.background(Color.Cyan.copy(0.2F))) {
mounted = innerPage()
// 设置前景图层
Box(
modifier = Modifier
.padding(bottom = 48.dp)
.size(56.dp)
.shadow(4.dp, CircleShape)
.background(Color.White)
.align(Alignment.BottomCenter),
) {
Text(
modifier = Modifier.align(Alignment.Center),
fontSize = 36.sp,
text = "❤️",
)
}
}
mounted
},
previewerLayer = TransformLayerScope(
previewerDecoration = { innerPreviewer ->
Box(
modifier = Modifier
.background(Color.Black)
) {
innerPreviewer.invoke()
}
}
),
)
LaunchedEffect(Unit) {
state.open()
}
}
@Composable
fun StateSample() {
// 参考
PreviewerSample.StateSample()
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/sample/ImageViewerSample.kt
================================================
package com.jvziyaoyao.scale.sample.sample
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import coil3.compose.rememberAsyncImagePainter
import com.jvziyaoyao.scale.image.viewer.AnyComposable
import com.jvziyaoyao.scale.image.viewer.ImageViewer
import com.jvziyaoyao.scale.image.viewer.ModelProcessor
import com.jvziyaoyao.scale.image.viewer.ModelProcessorPair
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableGestureScope
import com.jvziyaoyao.scale.zoomable.zoomable.rememberZoomableState
import org.jetbrains.compose.resources.painterResource
import scale.sample_kmp.generated.resources.Res
import scale.sample_kmp.generated.resources.light_02
object ImageViewerSample {
// 基本使用
@Composable
fun BasicSample() {
val painter = painterResource(Res.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ImageViewer(model = painter, state = state)
}
// 结合Coil使用
@Composable
fun CoilSample() {
val painter = rememberAsyncImagePainter(model = Res.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ImageViewer(model = painter, state = state)
}
// 显示一个Composable
@Composable
fun ComposableSample() {
val density = LocalDensity.current
val rectSize = 100.dp
val rectSizePx = density.run { rectSize.toPx() }
val size = Size(rectSizePx, rectSizePx)
val state = rememberZoomableState(contentSize = size)
ImageViewer(
state = state,
model = AnyComposable {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Cyan)
) {
Box(
modifier = Modifier
.fillMaxSize(0.6F)
.clip(CircleShape)
.background(Color.White)
.align(Alignment.BottomEnd)
)
Text(modifier = Modifier.align(Alignment.Center), text = "Hello Compose")
}
}
)
}
// 处理手势事件回调
@Composable
fun GestureSample() {
val painter = painterResource(Res.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ImageViewer(
model = painter,
state = state,
detectGesture = ZoomableGestureScope(
onTap = {}, // 长按事件
onDoubleTap = {}, // 双击事件
onLongPress = {}, // 长按事件
)
)
}
val stringProcessorPair: ModelProcessorPair = String::class to { model, _ ->
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.LightGray)
) {
Text(modifier = Modifier.align(Alignment.Center), text = model as String)
}
}
@Composable
fun ProcessSample() {
val message = "好家伙"
val state = rememberZoomableState(contentSize = Size(100F, 100F))
ImageViewer(
model = message,
state = state,
processor = ModelProcessor(stringProcessorPair)
)
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/sample/PreviewerSample.kt
================================================
package com.jvziyaoyao.scale.sample.sample
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil3.compose.rememberAsyncImagePainter
import com.jvziyaoyao.scale.zoomable.previewer.Previewer
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemView
import com.jvziyaoyao.scale.zoomable.previewer.TransformLayerScope
import com.jvziyaoyao.scale.zoomable.previewer.VerticalDragType
import com.jvziyaoyao.scale.zoomable.previewer.rememberPreviewerState
import com.jvziyaoyao.scale.zoomable.previewer.rememberTransformItemState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
object PreviewerSample {
// 简单使用
@Composable
fun BasicSample() {
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val state = rememberPreviewerState(pageCount = { images.size }) { images[it] }
Previewer(
state = state,
) { page ->
val painter = rememberAsyncImagePainter(model = images[page])
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
painter.intrinsicSize.isSpecified
}
LaunchedEffect(Unit) {
// 展开
state.open()
// 等待四秒
delay(4 * 1000)
// 关闭
state.close()
}
}
// 带转换动效
@Composable
fun TransformSample() {
val scope = rememberCoroutineScope()
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val state = rememberPreviewerState(pageCount = { images.size }) { images[it] }
Box(modifier = Modifier.fillMaxSize()) {
Row(
modifier = Modifier.align(Alignment.Center),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
images.forEachIndexed { index, url ->
val painter = rememberAsyncImagePainter(model = url)
val itemState =
rememberTransformItemState(intrinsicSize = painter.intrinsicSize)
TransformItemView(
modifier = Modifier
.size(120.dp)
.clickable {
scope.launch {
state.enterTransform(index)
}
},
key = url,
transformState = state,
itemState = itemState,
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
contentScale = ContentScale.Crop
)
}
}
}
}
Previewer(
state = state,
) { page ->
val painter = rememberAsyncImagePainter(model = images[page])
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
painter.intrinsicSize.isSpecified
}
}
// 编辑图层示例代码
@Composable
fun DecorationSample() {
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val state = rememberPreviewerState(pageCount = { images.size }) { images[it] }
Previewer(
state = state,
previewerLayer = TransformLayerScope(
previewerDecoration = {
// 设置组件的背景图层
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(0.2F))
) {
// 组件内容本身
it.invoke()
// 设置前景图层
Box(
modifier = Modifier
.padding(bottom = 48.dp)
.size(56.dp)
.shadow(4.dp, CircleShape)
.background(Color.White)
.align(Alignment.BottomCenter),
) {
Text(
modifier = Modifier.align(Alignment.Center),
fontSize = 36.sp,
text = "❤️",
)
}
}
},
),
) { page ->
val painter = rememberAsyncImagePainter(model = images[page])
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
if (!painter.intrinsicSize.isSpecified) {
// 加载中
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
painter.intrinsicSize.isSpecified
}
LaunchedEffect(Unit) {
state.open()
}
}
@Composable
fun StateSample() {
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val state = rememberPreviewerState(
// 垂直手势类型,支持上下拖拽关闭预览
verticalDragType = VerticalDragType.Down,
pageCount = { images.size },
getKey = { images[it] }
)
LaunchedEffect(Unit) {
state.open() // 展开
state.close() // 关闭
state.enterTransform(0) // 带转换动画展开
state.exitTransform() // 带转换动画关闭
state.visible // 当前组件是否可见
state.visibleTarget // 当前组件可见状态的目标值
state.animating // 是否正在进行动画
state.canOpen // 是否允许展开
state.canClose // 是否允许关闭
}
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/sample/SamplingDecoderSample.kt
================================================
package com.jvziyaoyao.scale.sample.sample
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import com.jvziyaoyao.scale.image.sampling.SamplingCanvas
import com.jvziyaoyao.scale.image.sampling.SamplingCanvasViewPort
import com.jvziyaoyao.scale.image.sampling.getViewPort
import com.jvziyaoyao.scale.image.sampling.rememberSamplingDecoder
import com.jvziyaoyao.scale.image.sampling.samplingProcessorPair
import com.jvziyaoyao.scale.image.viewer.ImageViewer
import com.jvziyaoyao.scale.image.viewer.ModelProcessor
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableView
import com.jvziyaoyao.scale.zoomable.zoomable.detectTransformGestures
import com.jvziyaoyao.scale.zoomable.zoomable.rememberZoomableState
import scale.sample_kmp.generated.resources.Res
object SamplingDecoderSample {
@Composable
fun BasicSample() {
val bytes = remember { mutableStateOf(null) }
LaunchedEffect(Unit) { bytes.value = Res.readBytes("files/a350.jpg") }
val (samplingDecoder) = rememberSamplingDecoder(bytes.value)
if (samplingDecoder != null) {
val state = rememberZoomableState(contentSize = samplingDecoder.intrinsicSize)
ImageViewer(
model = samplingDecoder,
state = state,
processor = ModelProcessor(samplingProcessorPair)
)
}
}
@Composable
fun ZoomableSample() {
val bytes = remember { mutableStateOf(null) }
LaunchedEffect(Unit) { bytes.value = Res.readBytes("files/a350.jpg") }
val (samplingDecoder) = rememberSamplingDecoder(bytes.value)
if (samplingDecoder != null) {
val state = rememberZoomableState(contentSize = samplingDecoder.intrinsicSize)
ZoomableView(state = state) {
SamplingCanvas(
samplingDecoder = samplingDecoder,
viewPort = state.getViewPort()
)
}
}
}
@Composable
fun RawSample() {
val bytes = remember { mutableStateOf(null) }
LaunchedEffect(Unit) { bytes.value = Res.readBytes("files/a350.jpg") }
val (samplingDecoder) = rememberSamplingDecoder(bytes.value)
if (samplingDecoder != null) {
val offset = remember { mutableStateOf(Offset.Zero) }
val scale = remember { mutableStateOf(1F) }
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, _, _ ->
offset.value += pan
scale.value *= zoom
true
}
}
) {
val ratio = samplingDecoder.intrinsicSize.run {
width.div(height)
}
Box(
modifier = Modifier
.graphicsLayer {
translationX = offset.value.x
translationY = offset.value.y
scaleX = scale.value
scaleY = scale.value
}
.fillMaxWidth()
.aspectRatio(ratio)
.align(Alignment.Center)
) {
SamplingCanvas(
samplingDecoder = samplingDecoder,
viewPort = SamplingCanvasViewPort(
scale = 8F,
visualRect = Rect(0.4F, 0.4F, 0.6F, 0.8F)
)
)
}
}
}
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/sample/ZoomablePagerSample.kt
================================================
package com.jvziyaoyao.scale.sample.sample
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import com.jvziyaoyao.scale.zoomable.pager.ZoomablePager
import com.jvziyaoyao.scale.zoomable.pager.rememberZoomablePagerState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import coil3.compose.rememberAsyncImagePainter
import com.jvziyaoyao.scale.zoomable.pager.PagerGestureScope
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.painterResource
import scale.sample_kmp.generated.resources.Res
import scale.sample_kmp.generated.resources.light_01
import scale.sample_kmp.generated.resources.light_02
object ZoomablePagerSample {
// 简单使用
@Composable
fun BasicSample() {
val images = remember {
mutableStateListOf(Res.drawable.light_01, Res.drawable.light_02)
}
val pagerState = rememberZoomablePagerState { images.size }
ZoomablePager(state = pagerState) { page ->
val painter = painterResource(images[page])
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) { _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
}
}
// Coil加载网络图片
@Composable
fun CoilSample() {
val images = remember {
mutableStateListOf(
"https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
"https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
)
}
val pagerState = rememberZoomablePagerState { images.size }
ZoomablePager(state = pagerState) { page ->
val painter = rememberAsyncImagePainter(model = images[page])
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) { _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
if (!painter.intrinsicSize.isSpecified) {
// 未加载成功时可以先显示一个loading占位
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
}
}
// 对页面进行自定义
@Composable
fun DecorationSample() {
val images = remember {
mutableStateListOf(Res.drawable.light_01, Res.drawable.light_02)
}
val pagerState = rememberZoomablePagerState { images.size }
ZoomablePager(state = pagerState) { page ->
val painter = painterResource(images[page])
// 设置背景色奇偶页不同
val backgroundColor = if (page % 2 == 0) Color.Cyan else Color.Gray
Box(
modifier = Modifier
.fillMaxSize()
.background(backgroundColor.copy(0.2F))
) {
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) { _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
// 设置每一页的前景图层
Box(
modifier = Modifier
.padding(bottom = 20.dp)
.clip(RoundedCornerShape(8.dp))
.background(Color.LightGray)
.padding(8.dp)
.align(Alignment.BottomCenter),
) {
Text(text = "${page + 1}/${images.size}")
}
}
}
}
@Composable
fun StateSample() {
val scope = rememberCoroutineScope()
val images = remember {
mutableStateListOf(Res.drawable.light_01, Res.drawable.light_02)
}
val pagerState = rememberZoomablePagerState { images.size }
ZoomablePager(
state = pagerState,
itemSpacing = 20.dp, // 设置页面的间隙
beyondViewportPageCount = 2, // 除当前页面外,预先加载其他页面的数量
detectGesture = PagerGestureScope(
onTap = {
// 点击事件
scope.launch {
// 获取当前页面的页码
if (pagerState.currentPage == 0) {
// 滚动到下一个页面
pagerState.animateScrollToPage(1)
// pagerState.scrollToPage(1)
}
}
},
onDoubleTap = {
// 双击事件
// 如果返回false,会执行默认操作,把当前页面放大到最大
// 如果返回true,则不会有任何操作
return@PagerGestureScope true
},
onLongPress = {
// 长按事件
}
)
) { page ->
val painter = painterResource(images[page])
ZoomablePolicy(intrinsicSize = painter.intrinsicSize) { _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null
)
}
}
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/sample/ZoomableViewSample.kt
================================================
package com.jvziyaoyao.scale.sample.sample
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import coil3.compose.rememberAsyncImagePainter
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableGestureScope
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableView
import com.jvziyaoyao.scale.zoomable.zoomable.rememberZoomableState
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.painterResource
import scale.sample_kmp.generated.resources.Res
import scale.sample_kmp.generated.resources.light_02
object ZoomableViewSample {
// 简单使用
@Composable
fun BasicSample() {
val painter = painterResource(Res.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ZoomableView(state = state) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
)
}
}
// 结合Coil使用
@Composable
fun CoilSample() {
val painter = rememberAsyncImagePainter(model = Res.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ZoomableView(state = state) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
)
}
}
// 显示一个Composable
@Composable
fun ComposableSample() {
val density = LocalDensity.current
val rectSize = 100.dp
val rectSizePx = density.run { rectSize.toPx() }
val size = Size(rectSizePx, rectSizePx)
val state = rememberZoomableState(contentSize = size)
ZoomableView(state = state) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Cyan)
) {
Box(
modifier = Modifier
.fillMaxSize(0.6F)
.clip(CircleShape)
.background(Color.White)
.align(Alignment.BottomEnd)
)
Text(modifier = Modifier.align(Alignment.Center), text = "Hello Compose")
}
}
}
// 处理手势事件回调
@Composable
fun GestureSample() {
val painter = painterResource(Res.drawable.light_02)
val state = rememberZoomableState(contentSize = painter.intrinsicSize)
ZoomableView(
state = state,
detectGesture = ZoomableGestureScope(
// 点击事件
onTap = { offset ->
},
// 双击事件
onDoubleTap = { offset ->
},
// 长按事件
onLongPress = { offset ->
}
)
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
)
}
}
@Composable
fun StateSample() {
val scope = rememberCoroutineScope()
val painter = painterResource(Res.drawable.light_02)
val state = rememberZoomableState(
contentSize = painter.intrinsicSize,
// 设置组件最大缩放率
maxScale = 4F,
// 设置组件进行动画时的动画规格
animationSpec = tween(1200)
)
state.isRunning() // 获取组件是否在动画状态
state.displaySize // 获取组件1倍显示的大小
state.scale // 获取组件当前相对于1倍显示大小的缩放率
state.offsetX // 获取组件的X轴位移
state.offsetY // 获取组件的Y轴位移
state.rotation // 获取组件旋转角度
ZoomableView(
state = state,
detectGesture = ZoomableGestureScope(
onDoubleTap = { offset ->
scope.launch {
// 在最大和最小显示倍率间切换,如果当前缩放率即不是最大值,
// 也不是最小值,会恢复到默认显示大小
state.toggleScale(offset)
}
},
onLongPress = { _ ->
// 恢复到默认显示大小
scope.launch { state.reset() }
}
)
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
)
}
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/ui/component/ImageLoader.kt
================================================
package com.jvziyaoyao.scale.sample.ui.component
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.painter.Painter
import coil3.compose.LocalPlatformContext
import coil3.compose.rememberAsyncImagePainter
import coil3.request.ImageRequest
import coil3.size.Size
@Composable
fun rememberCoilImagePainter(image: Any): Painter {
// 加载图片
val imageRequest = ImageRequest.Builder(LocalPlatformContext.current)
.data(image)
.size(Size.ORIGINAL)
.build()
// 获取图片的初始大小
return rememberAsyncImagePainter(imageRequest)
}
//suspend fun loadPainter(context: PlatformContext, data: Any) = suspendCoroutine { c ->
// val imageRequest = ImageRequest.Builder(context)
// .data(data)
// .size(coil.size.Size.ORIGINAL)
// .target(
// onSuccess = {
// c.resume(it)
// },
// onError = {
// c.resume(null)
// }
// )
// .build()
// context.imageLoader.enqueue(imageRequest)
//}
//@Composable
//fun rememberBitmapRegionDecoder(
// inputStream: InputStream,
//): BitmapRegionDecoder? {
// val decoder = remember { mutableStateOf(null) }
// LaunchedEffect(inputStream) {
// launch(Dispatchers.IO) {
// decoder.value = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// BitmapRegionDecoder.newInstance(inputStream)
// } else {
// BitmapRegionDecoder.newInstance(inputStream,false)
// }
// }
// }
// return decoder.value
//}
//
//@Composable
//fun rememberDecoderImagePainter(
// inputStream: InputStream,
// rotation: Int = 0,
// delay: Long? = null,
//): SamplingDecoder? {
// var samplingDecoder by remember { mutableStateOf(null) }
// LaunchedEffect(inputStream) {
// launch(Dispatchers.IO) {
// if (delay != null) delay(delay)
// samplingDecoder = try {
// val decoder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// BitmapRegionDecoder.newInstance(inputStream)
// } else {
// BitmapRegionDecoder.newInstance(inputStream,false)
// }
// if (decoder == null) {
// null
// } else {
// val decoderRotation = when(rotation) {
// SamplingDecoder.Rotation.ROTATION_90.radius -> SamplingDecoder.Rotation.ROTATION_90
// SamplingDecoder.Rotation.ROTATION_180.radius -> SamplingDecoder.Rotation.ROTATION_180
// SamplingDecoder.Rotation.ROTATION_270.radius -> SamplingDecoder.Rotation.ROTATION_270
// else -> SamplingDecoder.Rotation.ROTATION_0
// }
// SamplingDecoder(
// decoder = decoder,
// rotation = decoderRotation
// )
// }
// } catch (e: Exception) {
// e.printStackTrace()
// null
// }
// }
// }
// DisposableEffect(Unit) {
// onDispose {
// samplingDecoder?.release()
// }
// }
// return samplingDecoder
//}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/ui/component/ScaleGrid.kt
================================================
package com.jvziyaoyao.scale.sample.ui.component
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import kotlinx.coroutines.launch
const val DEFAULT_GRID_SCALE_SIZE = 0.84F
const val DEFAULT_LONG_PRESS_TIME = 400L
class DetectScaleGridGesture(
var onPress: () -> Unit = {},
var onLongPress: () -> Unit = {},
)
@Composable
fun ScaleGrid(
modifier: Modifier = Modifier,
scaleSize: Float = DEFAULT_GRID_SCALE_SIZE,
longPressTime: Long = DEFAULT_LONG_PRESS_TIME,
detectGesture: DetectScaleGridGesture? = null,
content: @Composable (Float) -> Unit = {},
) {
val scope = rememberCoroutineScope()
val itemScale = remember { Animatable(1F) }
Box(
modifier = modifier
.fillMaxSize()
.graphicsLayer {
scaleX = itemScale.value
scaleY = itemScale.value
}
.pointerInput(detectGesture) {
awaitEachGesture {
awaitFirstDown()
// 这里开始
scope.launch {
itemScale.animateTo(scaleSize)
}
try {
withTimeout(longPressTime) {
var move = false
do {
val event = awaitPointerEvent()
if (!move) {
move = event.type == PointerEventType.Move
break
}
} while (event.changes.any { it.pressed })
if (!move) {
detectGesture?.onPress?.invoke()
}
}
} catch (e: Exception) {
detectGesture?.onLongPress?.invoke()
}
// 这里结束
scope.launch {
itemScale.animateTo(1F)
}
}
}
) {
content(itemScale.value)
}
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/ui/theme/Layout.kt
================================================
package com.jvziyaoyao.scale.sample.ui.theme
/**
* @program: ImageGallery
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-07-28 19:50
**/
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* @program: ImageGallery
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-07-28 19:50
**/
class Padding(
val pxxs: Dp = 2.dp,
val pxs: Dp = 4.dp,
val ps: Dp = 8.dp,
val pm: Dp = 12.dp,
val pl: Dp = 20.dp,
val pxl: Dp = 36.dp,
val pxxl: Dp = 48.dp,
)
class FontSize(
val fxxs: TextUnit = 10.sp,
val fxs: TextUnit = 12.sp,
val fs: TextUnit = 14.sp,
val fm: TextUnit = 16.sp,
val fl: TextUnit = 18.sp,
val fxl: TextUnit = 24.sp,
val fxxl: TextUnit = 28.sp,
val fh: TextUnit = 32.sp,
)
class RoundShape(
val rs_dp: Dp = 6.dp,
val rm_dp: Dp = 12.dp,
val rl_dp: Dp = 18.dp,
val rxl_dp: Dp = 28.dp,
val rs: RoundedCornerShape = RoundedCornerShape(rs_dp),
val rm: RoundedCornerShape = RoundedCornerShape(rm_dp),
val rl: RoundedCornerShape = RoundedCornerShape(rl_dp),
val rxl: RoundedCornerShape = RoundedCornerShape(rxl_dp),
)
object Layout {
private val defaultPadding = Padding()
private val defaultFontSize = FontSize()
private val defaultRoundShape = RoundShape()
val padding: Padding
@Composable
get() = defaultPadding
val fontSize: FontSize
@Composable
get() = defaultFontSize
val roundShape: RoundShape
@Composable
get() = defaultRoundShape
}
================================================
FILE: sample-kmp/src/commonMain/kotlin/com/jvziyaoyao/scale/sample/ui/theme/Theme.kt
================================================
package com.jvziyaoyao.scale.sample.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.SliderColors
import androidx.compose.material.SliderDefaults
import androidx.compose.material.SwitchColors
import androidx.compose.material.SwitchDefaults
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.graphics.Color
import coil3.ImageLoader
import coil3.compose.setSingletonImageLoaderFactory
import coil3.request.crossfade
import coil3.util.Logger
val coilLogger = object : Logger {
override var minLevel: Logger.Level
get() = Logger.Level.Info
set(value) {}
override fun log(
tag: String,
level: Logger.Level,
message: String?,
throwable: Throwable?
) {
com.jvziyaoyao.scale.sample.base.log(msg = message ?: "无信息~", tag)
}
}
@Composable
fun getSwitchColors(): SwitchColors {
return SwitchDefaults.colors(checkedThumbColor = MaterialTheme.colorScheme.primary)
}
@Composable
fun getSlideColors(): SliderColors {
return SliderDefaults.colors(
thumbColor = MaterialTheme.colorScheme.primary,
activeTrackColor = MaterialTheme.colorScheme.primary,
)
}
@Composable
fun ScaleSampleTheme(
content: @Composable () -> Unit
) {
setSingletonImageLoaderFactory { context ->
ImageLoader.Builder(context)
.logger(coilLogger)
.crossfade(true)
.build()
}
val colorScheme = if (isSystemInDarkTheme()) {
darkColorScheme(
primary = Color(0xFFFFB641),
background = Color(0xFF060B14),
surface = Color(0xFF14325A),
onBackground = Color(0xFFFFFFFF),
)
} else {
lightColorScheme(
primary = Color(0xFF325491),
background = Color(0xFFE5E5E5),
surface = Color(0xFFFFFFFF),
onBackground = Color(0xFF000000),
)
}
MaterialTheme(
colorScheme = colorScheme,
) {
val contentColor = colorScheme.onBackground.copy(0.8F)
CompositionLocalProvider(
LocalTextStyle provides LocalTextStyle.current.copy(color = contentColor),
LocalContentColor provides contentColor,
) {
content()
}
}
}
================================================
FILE: sample-kmp/src/iosMain/kotlin/com/jvziyaoyao/scale/sample/ViewController.kt
================================================
package com.jvziyaoyao.scale.sample
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ExperimentalComposeApi
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.uikit.OnFocusBehavior
import androidx.compose.ui.window.ComposeUIViewController
import com.jvziyaoyao.scale.sample.page.TransformBody
import com.jvziyaoyao.scale.sample.page.DecoderBody
import com.jvziyaoyao.scale.sample.page.DuplicateBody
import com.jvziyaoyao.scale.sample.page.GalleryBody
import com.jvziyaoyao.scale.sample.page.HomeBody
import com.jvziyaoyao.scale.sample.page.HugeBody
import com.jvziyaoyao.scale.sample.page.NormalBody
import com.jvziyaoyao.scale.sample.page.PreviewerBody
import com.jvziyaoyao.scale.sample.page.ZoomableBody
import com.jvziyaoyao.scale.sample.ui.theme.ScaleSampleTheme
import platform.UIKit.UIViewController
@OptIn(ExperimentalComposeApi::class, ExperimentalComposeUiApi::class)
fun getBaseViewController(
opaque: Boolean = true,
onFocusBehavior: OnFocusBehavior = OnFocusBehavior.FocusableAboveKeyboard,
content: @Composable () -> Unit,
): UIViewController {
return ComposeUIViewController(
configure = {
this.opaque = opaque
this.delegate = delegate
this.onFocusBehavior = onFocusBehavior
this.enforceStrictPlistSanityCheck = false
}
) {
ScaleSampleTheme {
content()
}
}
}
fun homeViewController(
onZoomable: () -> Unit,
onNormal: () -> Unit,
onHuge: () -> Unit,
onGallery: () -> Unit,
onPreviewer: () -> Unit,
onTransform: () -> Unit,
onDecoder: () -> Unit,
onDuplicate: () -> Unit,
) = getBaseViewController {
HomeBody(
onZoomable = onZoomable,
onNormal = onNormal,
onHuge = onHuge,
onGallery = onGallery,
onPreviewer = onPreviewer,
onTransform = onTransform,
onDecoder = onDecoder,
onDuplicate = onDuplicate,
)
}
fun zoomableViewController() = getBaseViewController {
ZoomableBody()
}
fun normalViewController() = getBaseViewController {
NormalBody()
}
fun hugeViewController() = getBaseViewController {
HugeBody()
}
fun galleryViewController() = getBaseViewController {
GalleryBody()
}
fun previewerViewController() = getBaseViewController {
PreviewerBody {
}
}
fun transformViewController() = getBaseViewController {
TransformBody()
}
fun decoderViewController() = getBaseViewController {
DecoderBody()
}
fun duplicateViewController() = getBaseViewController {
DuplicateBody()
}
================================================
FILE: sample-kmp/src/iosMain/kotlin/com/jvziyaoyao/scale/sample/base/BaseMathod.ios.kt
================================================
package com.jvziyaoyao.scale.sample.base
import androidx.compose.runtime.Composable
actual fun log(msg: String, tag: String) {
println("$tag ========> $msg")
}
@Composable
actual fun BackHandler(enabled: Boolean, onBack: () -> Unit) {}
================================================
FILE: scale-image-viewer/.gitignore
================================================
/build
================================================
FILE: scale-image-viewer/build.gradle.kts
================================================
import scale.compileSdk
import scale.minSdk
plugins {
id("com.android.kotlin.multiplatform.library")
id("org.jetbrains.kotlin.plugin.compose")
id("org.jetbrains.kotlin.multiplatform")
id("com.vanniktech.maven.publish")
id("org.jetbrains.compose")
id("org.jetbrains.dokka")
}
kotlin {
androidLibrary {
namespace = "com.jvziyaoyao.scale.image"
compileSdk = project.compileSdk
minSdk = project.minSdk
}
jvm()
val xcfName = "imageViewerKit"
iosX64 {
binaries.framework {
baseName = xcfName
}
}
iosArm64 {
binaries.framework {
baseName = xcfName
}
}
iosSimulatorArm64 {
binaries.framework {
baseName = xcfName
}
}
sourceSets {
commonMain {
dependencies {
implementation(libs.kotlin.stdlib)
api(project(":scale-zoomable-view"))
implementation(libs.kotlin.stdlib)
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.ui)
implementation(compose.components.resources)
implementation(compose.components.uiToolingPreview)
implementation(libs.org.jetbrains.kotlinx.datetime)
}
}
commonTest {
dependencies {
implementation(libs.kotlin.test)
}
}
androidMain {
dependencies {}
}
iosMain {
dependencies {}
}
}
}
================================================
FILE: scale-image-viewer/gradle.properties
================================================
POM_ARTIFACT_ID=image-viewer
POM_NAME=image-viewer
POM_PACKAGING=aar
================================================
FILE: scale-image-viewer/src/commonMain/kotlin/com/jvziyaoyao/scale/image/pager/ImagePager.kt
================================================
package com.jvziyaoyao.scale.image.pager
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.TargetedFlingBehavior
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.jvziyaoyao.scale.image.viewer.AnyComposable
import com.jvziyaoyao.scale.image.viewer.ModelProcessor
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_ITEM_SPACE
import com.jvziyaoyao.scale.zoomable.pager.PagerGestureScope
import com.jvziyaoyao.scale.zoomable.pager.PagerZoomablePolicyScope
import com.jvziyaoyao.scale.zoomable.pager.ZoomablePager
import com.jvziyaoyao.scale.zoomable.pager.ZoomablePagerState
import com.jvziyaoyao.scale.zoomable.pager.defaultFlingBehavior
/**
* 基于Pager实现的图片浏览器
*
* @param modifier 图层修饰
* @param pagerState 控件状态与控制对象
* @param itemSpacing 每一页的间隔
* @param beyondViewportPageCount 超出视口的页面缓存的个数
* @param userScrollEnabled 是否允许页面滚动
* @param detectGesture 手势监听对象
* @param processor 用于解析图像数据的方法,可以自定义
* @param imageLoader 图像加载器,支持的图像类型与ImageViewer一致,如果需要支持其他类型的数据可以自定义processor
* @param imageLoading 图像未完成加载时的占位
* @param proceedPresentation 用于控制ZoomableView、Loading等图层的切换逻辑,可以自定义
* @param pageDecoration 每一页的图层修饰,可以用来设置页面的前景、背景等
*/
@Composable
fun ImagePager(
modifier: Modifier = Modifier,
pagerState: ZoomablePagerState,
itemSpacing: Dp = DEFAULT_ITEM_SPACE,
beyondViewportPageCount: Int = DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT,
flingBehavior: TargetedFlingBehavior = defaultFlingBehavior(pagerState.pagerState),
userScrollEnabled: Boolean = true,
detectGesture: PagerGestureScope = PagerGestureScope(),
processor: ModelProcessor = ModelProcessor(),
imageLoader: @Composable (Int) -> Pair,
imageLoading: ImageLoading? = defaultImageLoading,
proceedPresentation: ProceedPresentation = defaultProceedPresentation,
pageDecoration: @Composable (page: Int, innerPage: @Composable () -> Unit) -> Unit
= { _, innerPage -> innerPage() },
) {
ZoomablePager(
modifier = modifier,
state = pagerState,
itemSpacing = itemSpacing,
beyondViewportPageCount = beyondViewportPageCount,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled,
detectGesture = detectGesture,
) { page ->
pageDecoration.invoke(page) {
val (model, size) = imageLoader.invoke(page)
proceedPresentation.invoke(this, model, size, processor, imageLoading)
}
}
}
/**
* 用于控制ZoomableView、Loading等图层的切换
*/
typealias ProceedPresentation = @Composable PagerZoomablePolicyScope.(
model: Any?,
size: Size?,
processor: ModelProcessor,
imageLoading: ImageLoading?,
) -> Boolean
/**
* 默认ImageModelProcessor
*/
val defaultProceedPresentation: ProceedPresentation = { model, size, processor, imageLoading ->
// TODO 这里是否要添加渐变动画?
if (model != null && model is AnyComposable && size == null) {
model.composable.invoke()
true
} else if (model != null && size != null) {
ZoomablePolicy(intrinsicSize = size) {
processor.Deploy(model = model, state = it)
}
size.isSpecified
} else {
imageLoading?.invoke()
false
}
}
/**
* 图像未完成加载时的占位
*/
typealias ImageLoading = @Composable () -> Unit
/**
* 默认ImageLoading
*/
val defaultImageLoading: ImageLoading = {
Box(modifier = Modifier.fillMaxSize()) {
CanvasCircularLoadingIndicator(
modifier = Modifier
.size(48.dp)
.align(Alignment.Center),
color = Color.LightGray,
)
}
}
@Composable
fun CanvasCircularLoadingIndicator(
modifier: Modifier = Modifier.size(48.dp),
strokeWidth: Dp = 4.dp,
color: Color = Color.Blue
) {
val infiniteTransition = rememberInfiniteTransition()
// 头部旋转角度
val rotation = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(
tween(1333, easing = LinearEasing),
repeatMode = RepeatMode.Restart
)
)
// 尾部旋转角度
val sweep = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(
tween(1333, easing = LinearEasing),
repeatMode = RepeatMode.Restart
)
)
val reverse = remember { mutableStateOf(false) }
val lastSweep = remember { mutableStateOf(0F) }
Canvas(modifier = modifier) {
val stroke = Stroke(width = strokeWidth.toPx(), cap = StrokeCap.Round)
val diameter = size.minDimension
val arcSize = Size(diameter, diameter)
val topLeft = Offset(
(size.width - diameter) / 2f,
(size.height - diameter) / 2f
)
if (sweep.value - lastSweep.value < 0) {
reverse.value = !reverse.value
}
lastSweep.value = sweep.value
val startAngle = if (!reverse.value) 0F else sweep.value
val sweepAngle = if (!reverse.value) sweep.value else 360F - sweep.value
withTransform({ rotate(rotation.value) }) {
drawArc(
color = color,
startAngle = startAngle,
sweepAngle = sweepAngle,
useCenter = false,
topLeft = topLeft,
size = arcSize,
style = stroke
)
}
}
}
================================================
FILE: scale-image-viewer/src/commonMain/kotlin/com/jvziyaoyao/scale/image/previewer/ImagePreviewer.kt
================================================
package com.jvziyaoyao.scale.image.previewer
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import com.jvziyaoyao.scale.image.pager.ImageLoading
import com.jvziyaoyao.scale.image.pager.ProceedPresentation
import com.jvziyaoyao.scale.image.pager.defaultImageLoading
import com.jvziyaoyao.scale.image.pager.defaultProceedPresentation
import com.jvziyaoyao.scale.image.viewer.ModelProcessor
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_ITEM_SPACE
import com.jvziyaoyao.scale.zoomable.pager.PagerGestureScope
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_PREVIEWER_ENTER_TRANSITION
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_PREVIEWER_EXIT_TRANSITION
import com.jvziyaoyao.scale.zoomable.previewer.Previewer
import com.jvziyaoyao.scale.zoomable.previewer.PreviewerState
import com.jvziyaoyao.scale.zoomable.previewer.TransformLayerScope
/**
* 默认的容器背景
*/
val defaultPreviewBackground: (@Composable () -> Unit) = {
Box(
modifier = Modifier
.background(Color.Black)
.fillMaxSize()
)
}
/**
* 图片弹出预览组件
*
* @param modifier 图层修饰
* @param state 控件状态与控制对象
* @param itemSpacing 每一页的间隔
* @param beyondViewportPageCount 超出视口的页面缓存的个数
* @param enter 不使用转换效果时的弹出动效
* @param exit 不使用转换效果时的退出动效
* @param debugMode 调试模式,显示图层标识等
* @param detectGesture 手势监听对象
* @param processor 用于解析图像数据的方法,可以自定义
* @param imageLoader 图像加载器,支持的图像类型与ImageViewer一致,如果需要支持其他类型的数据可以自定义processor
* @param imageLoading 图像未完成加载时的占位
* @param imageModelProcessor 用于控制ZoomableView、Loading等图层的切换逻辑,可以自定义
* @param previewerLayer 预览器容器的自定义,可设置背景、前景等
* @param pageDecoration 每一页的图层修饰,可以用来设置页面的前景、背景等
*/
@Composable
fun ImagePreviewer(
modifier: Modifier = Modifier,
state: PreviewerState,
itemSpacing: Dp = DEFAULT_ITEM_SPACE,
beyondViewportPageCount: Int = DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT,
enter: EnterTransition = DEFAULT_PREVIEWER_ENTER_TRANSITION,
exit: ExitTransition = DEFAULT_PREVIEWER_EXIT_TRANSITION,
debugMode: Boolean = false,
detectGesture: PagerGestureScope = PagerGestureScope(),
processor: ModelProcessor = ModelProcessor(),
imageLoader: @Composable (Int) -> Pair,
imageLoading: ImageLoading? = defaultImageLoading,
proceedPresentation: ProceedPresentation = defaultProceedPresentation,
previewerLayer: TransformLayerScope = TransformLayerScope(
background = defaultPreviewBackground
),
pageDecoration: @Composable (page: Int, innerPage: @Composable () -> Boolean) -> Boolean
= { _, innerPage -> innerPage() },
) {
Previewer(
modifier = modifier,
state = state,
previewerLayer = previewerLayer,
itemSpacing = itemSpacing,
beyondViewportPageCount = beyondViewportPageCount,
enter = enter,
exit = exit,
debugMode = debugMode,
detectGesture = detectGesture,
zoomablePolicy = { page ->
pageDecoration.invoke(page) decoration@{
val (model, size) = imageLoader.invoke(page)
proceedPresentation.invoke(this, model, size, processor, imageLoading)
}
}
)
}
================================================
FILE: scale-image-viewer/src/commonMain/kotlin/com/jvziyaoyao/scale/image/previewer/TransformImageView.kt
================================================
package com.jvziyaoyao.scale.image.previewer
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import com.jvziyaoyao.scale.image.viewer.AnyComposable
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemView
import com.jvziyaoyao.scale.zoomable.previewer.TransformPreviewerState
import com.jvziyaoyao.scale.zoomable.previewer.rememberTransformItemState
/**
* 支持图片变换效果的ImageView,简单理解为:小图转换为大图动效中的小图
* 此接口的目的是方便开发者直接调用,如需更深入的定制化,推荐直接使用TransformItemView
*
* @param modifier 图层修饰
* @param imageLoader 图片加载器,Triple,
* 其中三个参数分别为:Key、图片数据、图片大小、
* 图片数据支持Painter、ImageBitmap、ImageVector、AnyComposable
* Key必须要与transformState中输入的key一致
* @param imageItemContent 用于解析图像数据的方法,可以自定义
* @param transformState TransformPreviewerState或其实现类
*/
@Composable
fun TransformImageView(
modifier: Modifier = Modifier,
imageLoader: @Composable () -> Triple,
imageItemContent: ImageItemContent = defaultImageItemContent,
transformState: TransformPreviewerState,
) {
val (key, model, size) = imageLoader.invoke()
val itemState =
rememberTransformItemState(intrinsicSize = size)
TransformItemView(
modifier = modifier,
key = key,
itemState = itemState,
transformState = transformState,
) {
imageItemContent.invoke(model)
}
}
/**
* 用于解析图像数据给TransformItemView显示的方法
*/
typealias ImageItemContent = @Composable (Any) -> Unit
/**
* 默认处理,当前model仅支持Painter、ImageBitmap、ImageVector、AnyComposable
*/
val defaultImageItemContent: ImageItemContent = { model ->
when (model) {
is Painter -> {
Image(
modifier = Modifier.fillMaxSize(),
painter = model,
contentScale = ContentScale.Crop,
contentDescription = null,
)
}
is ImageBitmap -> {
Image(
modifier = Modifier.fillMaxSize(),
bitmap = model,
contentScale = ContentScale.Crop,
contentDescription = null,
)
}
is ImageVector -> {
Image(
modifier = Modifier.fillMaxSize(),
imageVector = model,
contentScale = ContentScale.Crop,
contentDescription = null,
)
}
is AnyComposable -> {
model.composable.invoke()
}
}
}
================================================
FILE: scale-image-viewer/src/commonMain/kotlin/com/jvziyaoyao/scale/image/viewer/ImageViewer.kt
================================================
package com.jvziyaoyao.scale.image.viewer
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableGestureScope
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableView
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableViewState
import kotlin.reflect.KClass
/**
* 单个图片预览组件
*
* @param modifier 图层修饰
* @param model 需要显示的图像,默认支持Painter、ImageBitmap、ImageVector、AnyComposable,如果需要支持其他类型的数据可以自定义processor
* @param state 组件状态和控制类
* @param processor 将model数据渲染到界面上
* @param detectGesture 检测组件的手势交互
*/
@Composable
fun ImageViewer(
modifier: Modifier = Modifier,
model: Any?,
state: ZoomableViewState,
processor: ModelProcessor = ModelProcessor(),
detectGesture: ZoomableGestureScope = ZoomableGestureScope(),
) {
ZoomableView(
modifier = modifier,
state = state,
detectGesture = detectGesture,
) {
model?.let {
processor.Deploy(model = it, state = state)
}
}
}
/**
* 用于解析图像数据给ZoomableView显示的方法
*/
typealias ImageContent = @Composable (Any, ZoomableViewState) -> Unit
class ModelProcessor(
vararg additionalProcessor: ModelProcessorPair,
) {
private val typeMapper = mutableStateMapOf, ImageContent>()
init {
listOf(*basicModelProcessorList.toTypedArray(), *additionalProcessor).forEach { pair ->
typeMapper[pair.first] = pair.second
}
}
@Composable
fun Deploy(model: Any, state: ZoomableViewState) {
val entry = typeMapper.entries.firstOrNull { isSubclassOf(model, it.key) } ?: return
entry.value.invoke(model, state)
}
}
typealias ModelProcessorPair = Pair, ImageContent>
val basicModelProcessorList: List = listOf(
Painter::class to { model, _ ->
Image(
modifier = Modifier.fillMaxSize(),
painter = model as Painter,
contentDescription = null,
)
},
ImageBitmap::class to { model, _ ->
Image(
modifier = Modifier.fillMaxSize(),
bitmap = model as ImageBitmap,
contentDescription = null,
)
},
ImageVector::class to { model, _ ->
Image(
modifier = Modifier.fillMaxSize(),
imageVector = model as ImageVector,
contentDescription = null,
)
},
AnyComposable::class to { model, _ ->
(model as AnyComposable).composable.invoke()
}
)
/**
* 判断对象是否为某个类的子类
*
* @param T
* @param instance 当前实例
* @param kClass 需要匹配的类对象
* @return
*/
fun isSubclassOf(instance: T, kClass: KClass): Boolean {
return kClass.isInstance(instance)
}
/**
* ImageViewer传人的Model参数除了特定图片以外,还支持传人一个Composable函数
*
* @property composable
*/
class AnyComposable(val composable: @Composable () -> Unit)
================================================
FILE: scale-image-viewer-classic/.gitignore
================================================
/build
================================================
FILE: scale-image-viewer-classic/build.gradle.kts
================================================
import scale.compileSdk
import scale.minSdk
@Suppress("DSL_SCOPE_VIOLATION") // TODO: Remove once KTIJ-19369 is fixed
plugins {
id("org.jetbrains.kotlin.plugin.compose")
id("org.jetbrains.kotlin.android")
id("com.vanniktech.maven.publish")
id("com.android.library")
id("org.jetbrains.dokka")
}
android {
namespace = "com.origeek.imageViewer"
compileSdk = project.compileSdk
defaultConfig {
minSdk = project.minSdk
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = libs.versions.compose.compiler.get()
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
api("com.jvziyaoyao.scale:image-viewer:1.1.0-alpha.7")
api("com.jvziyaoyao.scale:sampling-decoder:1.1.0-alpha.7")
implementation(libs.androidx.compose.ui.util)
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.material)
implementation(libs.androidx.compose.ui.tooling.preview)
androidTestImplementation(libs.androidx.compose.ui.test)
debugImplementation(libs.androidx.compose.ui.tooling)
implementation(libs.core.ktx)
implementation(libs.appcompat)
implementation(libs.material)
testImplementation(libs.junit.junit)
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.espresso.core)
}
================================================
FILE: scale-image-viewer-classic/consumer-rules.pro
================================================
================================================
FILE: scale-image-viewer-classic/gradle.properties
================================================
POM_ARTIFACT_ID=image-viewer-classic
POM_NAME=image-viewer-classic
POM_PACKAGING=aar
================================================
FILE: scale-image-viewer-classic/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
================================================
FILE: scale-image-viewer-classic/src/androidTest/java/com/jvziyaoyao/scale/image/classic/ExampleInstrumentedTest.kt
================================================
package com.jvziyaoyao.scale.image.classic
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.jvziyaoyao.scale.image.classic.test", appContext.packageName)
}
}
================================================
FILE: scale-image-viewer-classic/src/main/AndroidManifest.xml
================================================
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/gallery/ImageGallery.kt
================================================
package com.origeek.imageViewer.gallery
import androidx.annotation.FloatRange
import androidx.annotation.IntRange
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_ITEM_SPACE
import com.jvziyaoyao.scale.zoomable.pager.SupportedHorizonPager
import com.jvziyaoyao.scale.zoomable.pager.SupportedPagerState
import com.jvziyaoyao.scale.zoomable.pager.rememberSupportedPagerState
import com.origeek.imageViewer.viewer.ImageViewer
import com.origeek.imageViewer.viewer.ImageViewerState
import com.origeek.imageViewer.viewer.commonDeprecatedText
import com.origeek.imageViewer.viewer.rememberViewerState
import kotlinx.coroutines.launch
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-10-10 11:50
**/
/**
* gallery手势对象
*/
@Deprecated(
message = commonDeprecatedText,
)
class GalleryGestureScope(
// 点击事件
var onTap: () -> Unit = {},
// 双击事件
var onDoubleTap: () -> Boolean = { false },
// 长按事件
var onLongPress: () -> Unit = {},
)
/**
* gallery图层对象
*/
@Deprecated(
message = commonDeprecatedText,
)
class GalleryLayerScope(
// viewer图层
var viewerContainer: @Composable (
page: Int, viewerState: ImageViewerState, viewer: @Composable () -> Unit
) -> Unit = { _, _, viewer -> viewer() },
// 背景图层
var background: @Composable ((Int) -> Unit) = {},
// 前景图层
var foreground: @Composable ((Int) -> Unit) = {},
)
/**
* gallery状态
*/
@Deprecated(
message = commonDeprecatedText,
)
open class ImageGalleryState(
val pagerState: SupportedPagerState,
) {
/**
* 当前viewer的状态
*/
var imageViewerState by mutableStateOf(null)
internal set
/**
* 当前页码
*/
val currentPage: Int
get() = pagerState.currentPage
/**
* 目标页码
*/
val targetPage: Int
get() = pagerState.targetPage
/**
* 总页数
*/
val pageCount: Int
get() = pagerState.pageCount
/**
* interactionSource
*/
val interactionSource: InteractionSource
get() = pagerState.interactionSource
/**
* 滚动到指定页面
* @param page Int
* @param pageOffset Float
*/
suspend fun scrollToPage(
@IntRange(from = 0) page: Int,
@FloatRange(from = 0.0, to = 1.0) pageOffset: Float = 0f,
) = pagerState.scrollToPage(page, pageOffset)
/**
* 动画滚动到指定页面
* @param page Int
* @param pageOffset Float
*/
suspend fun animateScrollToPage(
@IntRange(from = 0) page: Int,
@FloatRange(from = 0.0, to = 1.0) pageOffset: Float = 0f,
) = pagerState.animateScrollToPage(page, pageOffset)
}
/**
* 记录gallery状态
*/
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun rememberImageGalleryState(
@IntRange(from = 0) initialPage: Int = 0,
pageCount: () -> Int,
): ImageGalleryState {
val imagePagerState =
rememberSupportedPagerState(initialPage, pageCount)
return remember { ImageGalleryState(imagePagerState) }
}
/**
* 图片gallery,基于Pager实现的一个图片查看列表组件
*/
@Deprecated(
message = "方法已弃用,请使用:com.jvziyaoyao.image.pager.ImagePager",
)
@Composable
fun ImageGallery(
// 编辑参数
modifier: Modifier = Modifier,
// gallery状态
state: ImageGalleryState,
// 图片加载器
imageLoader: @Composable (Int) -> Any?,
// 每张图片之间的间隔
itemSpacing: Dp = DEFAULT_ITEM_SPACE,
// 检测手势
detectGesture: GalleryGestureScope.() -> Unit = {},
// gallery图层
galleryLayer: GalleryLayerScope.() -> Unit = {},
) {
// require(count >= 0) { "imageCount must be >= 0" }
val scope = rememberCoroutineScope()
// 手势相关
val galleryGestureScope = remember { GalleryGestureScope() }
detectGesture.invoke(galleryGestureScope)
// 图层相关
val galleryLayerScope = remember { GalleryLayerScope() }
galleryLayer.invoke(galleryLayerScope)
// 确保不会越界
val currentPage = state.currentPage
Box(
modifier = modifier
.fillMaxSize()
) {
galleryLayerScope.background(currentPage)
SupportedHorizonPager(
state = state.pagerState,
modifier = Modifier
.fillMaxSize(),
itemSpacing = itemSpacing,
) { page ->
val imageState = rememberViewerState()
LaunchedEffect(key1 = currentPage) {
if (currentPage != page) imageState.reset()
if (currentPage == page) {
state.imageViewerState = imageState
}
}
galleryLayerScope.viewerContainer(page, imageState) {
Box(
modifier = Modifier
.fillMaxSize(),
) {
key(page) {
ImageViewer(
modifier = Modifier.fillMaxSize(),
model = imageLoader(page),
state = imageState,
boundClip = false,
detectGesture = {
this.onTap = {
galleryGestureScope.onTap()
}
this.onDoubleTap = {
val consumed = galleryGestureScope.onDoubleTap()
if (!consumed) scope.launch {
imageState.toggleScale(it)
}
}
this.onLongPress = { galleryGestureScope.onLongPress() }
},
)
}
}
}
}
galleryLayerScope.foreground(currentPage)
}
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/previewer/ImagePreviewer.kt
================================================
package com.origeek.imageViewer.previewer
import androidx.annotation.IntRange
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.mapSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.Dp
import com.jvziyaoyao.scale.image.previewer.defaultPreviewBackground
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_ITEM_SPACE
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_PREVIEWER_ENTER_TRANSITION
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_PREVIEWER_EXIT_TRANSITION
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_SOFT_ANIMATION_SPEC
import com.jvziyaoyao.scale.zoomable.previewer.ItemStateMap
import com.jvziyaoyao.scale.zoomable.previewer.LocalTransformItemStateMap
import com.jvziyaoyao.scale.zoomable.previewer.VerticalDragType
import com.origeek.imageViewer.gallery.GalleryGestureScope
import com.origeek.imageViewer.gallery.ImageGallery
import com.origeek.imageViewer.gallery.ImageGalleryState
import com.origeek.imageViewer.gallery.rememberImageGalleryState
import com.origeek.imageViewer.viewer.ImageViewerState
import com.origeek.imageViewer.viewer.commonDeprecatedText
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
/**
* 预览组件的状态
*/
@Deprecated(
message = commonDeprecatedText,
)
class ImagePreviewerState(
// 协程作用域
scope: CoroutineScope = MainScope(),
// 默认动画窗格
defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
// 预览状态
galleryState: ImageGalleryState,
// 用于获取transformItemState
itemStateMap: ItemStateMap,
) : PreviewerVerticalDragState(
scope,
defaultAnimationSpec,
galleryState = galleryState,
itemStateMap = itemStateMap
) {
companion object {
fun getSaver(
galleryState: ImageGalleryState,
itemStateMap: ItemStateMap
): Saver {
return mapSaver(
save = {
mapOf(
it::currentPage.name to it.currentPage,
it::animateContainerVisibleState.name to it.animateContainerVisibleState.currentState,
it::uiAlpha.name to it.uiAlpha.value,
it::visible.name to it.visible,
)
},
restore = {
val previewerState = ImagePreviewerState(
galleryState = galleryState,
itemStateMap = itemStateMap
)
previewerState.animateContainerVisibleState =
MutableTransitionState(it[ImagePreviewerState::animateContainerVisibleState.name] as Boolean)
previewerState.uiAlpha =
Animatable(it[ImagePreviewerState::uiAlpha.name] as Float)
previewerState.visible = it[ImagePreviewerState::visible.name] as Boolean
previewerState
}
)
}
}
}
/**
* 记录预览组件状态
*/
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun rememberPreviewerState(
// 协程作用域
scope: CoroutineScope = rememberCoroutineScope(),
// 动画窗格
animationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
// 开启垂直手势的类型
verticalDragType: VerticalDragType = VerticalDragType.None,
// 初始页码
@IntRange(from = 0) initialPage: Int = 0,
// 获取页数
pageCount: () -> Int,
// 提供给组件用于获取key的方法
getKey: ((Int) -> Any)? = null,
): ImagePreviewerState {
val itemStateMap = LocalTransformItemStateMap.current
val galleryState = rememberImageGalleryState(initialPage, pageCount)
val imagePreviewerState =
rememberSaveable(saver = ImagePreviewerState.getSaver(galleryState, itemStateMap)) {
ImagePreviewerState(galleryState = galleryState, itemStateMap = itemStateMap)
}
imagePreviewerState.scope = scope
imagePreviewerState.getKey = getKey
imagePreviewerState.defaultAnimationSpec = animationSpec
imagePreviewerState.verticalDragType = verticalDragType
return imagePreviewerState
}
// 默认淡入淡出动画窗格
val DEFAULT_CROSS_FADE_ANIMATE_SPEC: AnimationSpec = tween(80)
// 加载占位默认的进入动画
val DEFAULT_PLACEHOLDER_ENTER_TRANSITION = fadeIn(tween(200))
// 加载占位默认的退出动画
val DEFAULT_PLACEHOLDER_EXIT_TRANSITION = fadeOut(tween(200))
// 默认的加载占位
val DEFAULT_PREVIEWER_PLACEHOLDER_CONTENT = @Composable {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(color = Color.White.copy(0.2F))
}
}
@Deprecated(
message = commonDeprecatedText,
)
// 加载时的占位内容
class PreviewerPlaceholder(
// 进入动画
var enterTransition: EnterTransition = DEFAULT_PLACEHOLDER_ENTER_TRANSITION,
// 退出动画
var exitTransition: ExitTransition = DEFAULT_PLACEHOLDER_EXIT_TRANSITION,
// 占位的内容
var content: @Composable () -> Unit = DEFAULT_PREVIEWER_PLACEHOLDER_CONTENT,
)
/**
* 预览图层对象
*/
@Deprecated(
message = commonDeprecatedText,
)
class PreviewerLayerScope(
// 包裹viewer的容器图层
var viewerContainer: @Composable (
page: Int, viewerState: ImageViewerState, viewer: @Composable () -> Unit
) -> Unit = { _, _, viewer -> viewer() },
// 背景图层
var background: @Composable ((page: Int) -> Unit) = { _ -> defaultPreviewBackground() },
// 前景图层
var foreground: @Composable ((page: Int) -> Unit) = { _ -> },
// 加载时的占位内容
var placeholder: PreviewerPlaceholder = PreviewerPlaceholder()
)
/**
* 图片预览组件
*/
@Deprecated(
message = "方法已弃用,请使用:com.jvziyaoyao.image.previewer.ImagePreviewer",
)
@Composable
fun ImagePreviewer(
// 编辑参数
modifier: Modifier = Modifier,
// 状态对象
state: ImagePreviewerState,
// 图片加载器
imageLoader: @Composable (Int) -> Any?,
// 图片间的间隔
itemSpacing: Dp = DEFAULT_ITEM_SPACE,
// 进入动画
enter: EnterTransition = DEFAULT_PREVIEWER_ENTER_TRANSITION,
// 退出动画
exit: ExitTransition = DEFAULT_PREVIEWER_EXIT_TRANSITION,
// 检测手势
detectGesture: GalleryGestureScope.() -> Unit = {},
// 自定义previewer的各个图层
previewerLayer: PreviewerLayerScope.() -> Unit = {},
) {
state.apply {
// 图层相关
val layerScope = remember { PreviewerLayerScope() }
previewerLayer.invoke(layerScope)
LaunchedEffect(
key1 = animateContainerVisibleState,
key2 = animateContainerVisibleState.currentState
) {
onAnimateContainerStateChanged()
}
AnimatedVisibility(
modifier = Modifier.fillMaxSize(),
visibleState = animateContainerVisibleState,
enter = enterTransition ?: enter,
exit = exitTransition ?: exit,
) {
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(getKey) {
verticalDrag(this)
}
) {
@Composable
fun UIContainer(content: @Composable () -> Unit) {
Box(
modifier = Modifier
.fillMaxSize()
.alpha(uiAlpha.value)
) {
content()
}
}
ImageGallery(
modifier = modifier.fillMaxSize(),
state = galleryState,
imageLoader = imageLoader,
itemSpacing = itemSpacing,
detectGesture = detectGesture,
galleryLayer = {
this.viewerContainer = { page, viewerState, viewer ->
layerScope.viewerContainer(page, viewerState) {
val viewerContainerState = rememberViewerContainerState(
viewerState = viewerState,
animationSpec = defaultAnimationSpec
)
LaunchedEffect(key1 = currentPage) {
if (currentPage == page) {
state.viewerContainerState = viewerContainerState
}
}
ImageViewerContainer(
modifier = Modifier.alpha(viewerAlpha.value),
containerState = viewerContainerState,
placeholder = layerScope.placeholder,
viewer = viewer,
)
}
}
this.background = {
UIContainer {
layerScope.background(it)
}
}
this.foreground = {
UIContainer {
layerScope.foreground(it)
}
}
},
)
if (!visible)
Box(modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) { detectTapGestures { } }) { }
}
}
ticket.Next()
}
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/previewer/ImageTransform.kt
================================================
package com.origeek.imageViewer.previewer
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntSize
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_SOFT_ANIMATION_SPEC
import com.jvziyaoyao.scale.zoomable.previewer.ItemStateMap
import com.jvziyaoyao.scale.zoomable.previewer.LocalTransformItemStateMap
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemState
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemView
import com.jvziyaoyao.scale.zoomable.previewer.rememberTransformItemState
import com.origeek.imageViewer.viewer.commonDeprecatedText
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-09-22 10:13
**/
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun TransformImageView(
modifier: Modifier = Modifier,
painter: Painter,
key: Any,
itemState: TransformItemState = rememberTransformItemState(),
previewerState: ImagePreviewerState,
) {
TransformImageView(
modifier = modifier,
key = key,
itemState = itemState,
contentState = previewerState.transformState,
) { itemKey ->
key(itemKey) {
LaunchedEffect(key1 = painter.intrinsicSize) {
if (painter.intrinsicSize.isSpecified) {
itemState.intrinsicSize = painter.intrinsicSize
}
}
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = null,
contentScale = ContentScale.Crop,
)
}
}
}
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun TransformImageView(
modifier: Modifier = Modifier,
bitmap: ImageBitmap,
key: Any,
itemState: TransformItemState = rememberTransformItemState(),
previewerState: ImagePreviewerState,
) {
TransformImageView(
modifier = modifier,
key = key,
itemState = itemState,
previewerState = previewerState,
) {
itemState.intrinsicSize = Size(
bitmap.width.toFloat(),
bitmap.height.toFloat()
)
Image(
modifier = Modifier.fillMaxSize(),
bitmap = bitmap,
contentDescription = null,
contentScale = ContentScale.Crop,
)
}
}
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun TransformImageView(
modifier: Modifier = Modifier,
imageVector: ImageVector,
key: Any,
itemState: TransformItemState = rememberTransformItemState(),
previewerState: ImagePreviewerState,
) {
TransformImageView(
modifier = modifier,
key = key,
itemState = itemState,
previewerState = previewerState,
) {
LocalDensity.current.run {
itemState.intrinsicSize = Size(
imageVector.defaultWidth.toPx(),
imageVector.defaultHeight.toPx(),
)
}
Image(
modifier = Modifier.fillMaxSize(),
imageVector = imageVector,
contentDescription = null,
contentScale = ContentScale.Crop,
)
}
}
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun TransformImageView(
modifier: Modifier = Modifier,
key: Any,
itemState: TransformItemState = rememberTransformItemState(),
previewerState: ImagePreviewerState,
content: @Composable (Any) -> Unit,
) = TransformImageView(modifier, key, itemState, previewerState.transformState, content)
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun TransformImageView(
modifier: Modifier = Modifier,
key: Any,
itemState: TransformItemState = rememberTransformItemState(),
contentState: TransformContentState? = rememberTransformContentState(),
content: @Composable (Any) -> Unit,
) {
TransformItemView(
modifier = modifier,
key = key,
itemState = itemState,
contentState = contentState,
) {
content(key)
}
}
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun TransformItemView(
modifier: Modifier = Modifier,
key: Any,
itemState: TransformItemState = rememberTransformItemState(),
contentState: TransformContentState?,
content: @Composable (Any) -> Unit,
) {
TransformItemView(
modifier = modifier,
key = key,
itemState = itemState,
itemVisible = contentState?.itemState != itemState || !contentState.onAction,
content = content,
)
}
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun TransformContentView(
transformContentState: TransformContentState = rememberTransformContentState(),
) {
Box(
modifier = Modifier
.fillMaxSize()
.onGloballyPositioned {
transformContentState.containerSize = it.size
transformContentState.containerOffset = it.positionInRoot()
},
) {
if (
transformContentState.srcCompose != null
&& transformContentState.onAction
) {
Box(
modifier = Modifier
.offset(
x = LocalDensity.current.run { (transformContentState.offsetX.value).toDp() },
y = LocalDensity.current.run { (transformContentState.offsetY.value).toDp() },
)
.size(
width = LocalDensity.current.run { transformContentState.displayWidth.value.toDp() },
height = LocalDensity.current.run { transformContentState.displayHeight.value.toDp() },
)
.graphicsLayer {
transformOrigin = TransformOrigin(0F, 0F)
scaleX = transformContentState.graphicScaleX.value
scaleY = transformContentState.graphicScaleY.value
},
) {
transformContentState.srcCompose!!(transformContentState.itemState?.key ?: Unit)
}
}
}
}
@Deprecated(
message = commonDeprecatedText,
)
class TransformContentState(
// 协程作用域
var scope: CoroutineScope = MainScope(),
// 默认动画窗格
var defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
// 用于获取transformItemState
var itemStateMap: ItemStateMap,
) {
var itemState: TransformItemState? by mutableStateOf(null)
val intrinsicSize: Size
get() = itemState?.intrinsicSize ?: Size.Zero
val intrinsicRatio: Float
get() {
if (intrinsicSize.height == 0F) return 1F
return intrinsicSize.width.div(intrinsicSize.height)
}
val srcPosition: Offset
get() {
val offset = itemState?.blockPosition ?: Offset.Zero
return offset.copy(x = offset.x - containerOffset.x, y = offset.y - containerOffset.y)
}
val srcSize: IntSize
get() = itemState?.blockSize ?: IntSize.Zero
val srcCompose: (@Composable (Any) -> Unit)?
get() = itemState?.blockCompose
var onAction by mutableStateOf(false)
var onActionTarget by mutableStateOf(null)
var displayWidth = Animatable(0F)
var displayHeight = Animatable(0F)
var graphicScaleX = Animatable(1F)
var graphicScaleY = Animatable(1F)
var offsetX = Animatable(0F)
var offsetY = Animatable(0F)
var containerOffset by mutableStateOf(Offset.Zero)
private var containerSizeState = mutableStateOf(IntSize.Zero)
var containerSize: IntSize
get() = containerSizeState.value
set(value) {
containerSizeState.value = value
if (value.width != 0 && value.height != 0) {
scope.launch {
specifierSizeFlow.emit(true)
}
}
}
var specifierSizeFlow = MutableStateFlow(false)
val containerRatio: Float
get() {
if (containerSize.height == 0) return 1F
return containerSize.width.toFloat().div(containerSize.height)
}
val widthFixed: Boolean
get() = intrinsicRatio > containerRatio
val fitSize: Size
get() {
return if (intrinsicRatio > containerRatio) {
// 宽度一致
val uW = containerSize.width
val uH = uW / intrinsicRatio
Size(uW.toFloat(), uH)
} else {
// 高度一致
val uH = containerSize.height
val uW = uH * intrinsicRatio
Size(uW, uH.toFloat())
}
}
val fitOffsetX: Float
get() {
return (containerSize.width - fitSize.width).div(2)
}
val fitOffsetY: Float
get() {
return (containerSize.height - fitSize.height).div(2)
}
val fitScale: Float
get() {
return fitSize.width.div(displayRatioSize.width)
}
val displayRatioSize: Size
get() {
return Size(width = srcSize.width.toFloat(), height = srcSize.width.div(intrinsicRatio))
}
val realSize: Size
get() {
return Size(
width = displayWidth.value * graphicScaleX.value,
height = displayHeight.value * graphicScaleY.value,
)
}
suspend fun awaitContainerSizeSpecifier() {
specifierSizeFlow.takeWhile { !it }.collect {}
}
fun findTransformItem(key: Any) = itemStateMap[key]
fun clearTransformItems() = itemStateMap.clear()
fun setEnterState() {
onAction = true
onActionTarget = null
}
fun setExitState() {
onAction = false
onActionTarget = null
}
suspend fun notifyEnterChanged() {
scope.launch {
listOf(
scope.async {
displayWidth.snapTo(displayRatioSize.width)
},
scope.async {
displayHeight.snapTo(displayRatioSize.height)
},
scope.async {
graphicScaleX.snapTo(fitScale)
},
scope.async {
graphicScaleY.snapTo(fitScale)
},
scope.async {
offsetX.snapTo(fitOffsetX)
},
scope.async {
offsetY.snapTo(fitOffsetY)
},
).awaitAll()
}
}
suspend fun exitTransform(
animationSpec: AnimationSpec? = null
) = suspendCoroutine { c ->
val currentAnimateSpec = animationSpec ?: defaultAnimationSpec
scope.launch {
listOf(
scope.async {
displayWidth.animateTo(srcSize.width.toFloat(), currentAnimateSpec)
},
scope.async {
displayHeight.animateTo(srcSize.height.toFloat(), currentAnimateSpec)
},
scope.async {
graphicScaleX.animateTo(1F, currentAnimateSpec)
},
scope.async {
graphicScaleY.animateTo(1F, currentAnimateSpec)
},
scope.async {
offsetX.animateTo(srcPosition.x, currentAnimateSpec)
},
scope.async {
offsetY.animateTo(srcPosition.y, currentAnimateSpec)
},
).awaitAll()
onAction = false
onActionTarget = null
c.resume(Unit)
}
}
suspend fun enterTransform(
itemState: TransformItemState,
animationSpec: AnimationSpec? = null
) = suspendCoroutine { c ->
val currentAnimationSpec = animationSpec ?: defaultAnimationSpec
this.itemState = itemState
displayWidth = Animatable(srcSize.width.toFloat())
displayHeight = Animatable(srcSize.height.toFloat())
graphicScaleX = Animatable(1F)
graphicScaleY = Animatable(1F)
offsetX = Animatable(srcPosition.x)
offsetY = Animatable(srcPosition.y)
onActionTarget = true
onAction = true
scope.launch {
reset(currentAnimationSpec)
c.resume(Unit)
onActionTarget = null
}
}
suspend fun reset(animationSpec: AnimationSpec? = null) {
val currentAnimationSpec = animationSpec ?: defaultAnimationSpec
listOf(
scope.async {
displayWidth.animateTo(displayRatioSize.width, currentAnimationSpec)
},
scope.async {
displayHeight.animateTo(displayRatioSize.height, currentAnimationSpec)
},
scope.async {
graphicScaleX.animateTo(fitScale, currentAnimationSpec)
},
scope.async {
graphicScaleY.animateTo(fitScale, currentAnimationSpec)
},
scope.async {
offsetX.animateTo(fitOffsetX, currentAnimationSpec)
},
scope.async {
offsetY.animateTo(fitOffsetY, currentAnimationSpec)
},
).awaitAll()
}
companion object {
val Saver: Saver = listSaver(
save = {
listOf(
it.onAction,
)
},
restore = {
val transformContentState =
TransformContentState(itemStateMap = mutableMapOf())
transformContentState.onAction = it[0] as Boolean
transformContentState
}
)
}
}
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun rememberTransformContentState(
scope: CoroutineScope = rememberCoroutineScope(),
animationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC
): TransformContentState {
val transformItemState = LocalTransformItemStateMap.current
val transformContentState = rememberSaveable(saver = TransformContentState.Saver) {
TransformContentState(itemStateMap = transformItemState)
}
transformContentState.scope = scope
transformContentState.defaultAnimationSpec = animationSpec
return transformContentState
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/previewer/ImageViewerContainer.kt
================================================
package com.origeek.imageViewer.previewer
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.mapSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.unit.IntSize
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_SOFT_ANIMATION_SPEC
import com.jvziyaoyao.scale.zoomable.previewer.LocalTransformItemStateMap
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemState
import com.origeek.imageViewer.viewer.ImageViewerState
import com.origeek.imageViewer.viewer.commonDeprecatedText
import com.origeek.imageViewer.viewer.rememberViewerState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.withContext
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-10-17 14:45
**/
@Deprecated(
message = commonDeprecatedText,
)
internal class ViewerContainerState(
// 协程作用域
var scope: CoroutineScope = MainScope(),
// 转换图层的状态
var transformState: TransformContentState,
// viewer的状态
var imageViewerState: ImageViewerState = ImageViewerState(),
// 默认动画窗格
var defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC
) {
/**
* +-------------------+
* INTERNAL
* +-------------------+
*/
// 转换图层transformContent透明度
internal var transformContentAlpha = Animatable(0F)
// viewer容器的透明度
internal var viewerContainerAlpha = Animatable(1F)
// 是否允许界面显示loading
internal var allowLoading by mutableStateOf(true)
// 打开图片后到加载成功过程的协程任务
internal var openTransformJob: Deferred? = null
/**
* 取消打开动作
*/
internal fun cancelOpenTransform() {
openTransformJob?.cancel()
openTransformJob = null
}
/**
* 等待挂载成功
*/
internal suspend fun awaitOpenTransform() {
// 这里需要等待viewer挂载,显示loading界面
openTransformJob = scope.async {
// 等待viewer加载
awaitViewerLoading()
// viewer加载成功后显示viewer
transformSnapToViewer(true)
}
openTransformJob?.await()
openTransformJob = null
}
/**
* 等待viewer挂载成功
*/
internal suspend fun awaitViewerLoading() {
imageViewerState.mountedFlow.apply {
withContext(Dispatchers.Default) {
takeWhile { !it }.collect()
}
}
}
/**
* 转换图层转viewer图层,true显示viewer,false显示转换图层
* @param isViewer Boolean
*/
internal suspend fun transformSnapToViewer(isViewer: Boolean) {
if (isViewer) {
transformContentAlpha.snapTo(0F)
viewerContainerAlpha.snapTo(1F)
} else {
transformContentAlpha.snapTo(1F)
viewerContainerAlpha.snapTo(0F)
}
}
/**
* 将viewer容器的位置大小复制给transformContent
*/
internal suspend fun copyViewerContainerStateToTransformState() {
transformState.apply {
val targetScale = scale.value * fitScale
graphicScaleX.snapTo(targetScale)
graphicScaleY.snapTo(targetScale)
val centerOffsetY = (containerSize.height - realSize.height).div(2)
val centerOffsetX = (containerSize.width - realSize.width).div(2)
offsetY.snapTo(centerOffsetY + this@ViewerContainerState.offsetY.value)
offsetX.snapTo(centerOffsetX + this@ViewerContainerState.offsetX.value)
}
}
/**
* 将viewer的位置大小等信息复制给transformContent
* @param itemState TransformItemState
*/
internal suspend fun copyViewerPosToContent(itemState: TransformItemState) {
transformState.apply {
// 更新itemState,确保itemState一致
this@apply.itemState = itemState
// 确保viewer的容器大小与transform的容器大小一致
containerSize = imageViewerState.containerSize
val scale = imageViewerState.scale
val offsetX = imageViewerState.offsetX
val offsetY = imageViewerState.offsetY
// 计算transform的实际大小
val rw = fitSize.width * scale.value
val rh = fitSize.height * scale.value
// 计算目标平移量
val goOffsetX =
(containerSize.width - rw).div(2) + offsetX.value
val goOffsetY =
(containerSize.height - rh).div(2) + offsetY.value
// 计算缩放率
val fixScale = fitScale * scale.value
// 更新值
graphicScaleX.snapTo(fixScale)
graphicScaleY.snapTo(fixScale)
displayWidth.snapTo(displayRatioSize.width)
displayHeight.snapTo(displayRatioSize.height)
this@apply.offsetX.snapTo(goOffsetX)
this@apply.offsetY.snapTo(goOffsetY)
}
}
// 容器大小
var containerSize: IntSize by mutableStateOf(IntSize.Zero)
// 容器的偏移量X
var offsetX = Animatable(0F)
// 容器的偏移量Y
var offsetY = Animatable(0F)
// 容器缩放
var scale = Animatable(1F)
/**
* 重置回原来的状态
* @param animationSpec AnimationSpec
*/
suspend fun reset(animationSpec: AnimationSpec = defaultAnimationSpec) {
scope.apply {
listOf(
async {
offsetX.animateTo(0F, animationSpec)
},
async {
offsetY.animateTo(0F, animationSpec)
},
async {
scale.animateTo(1F, animationSpec)
},
).awaitAll()
}
}
/**
* 立刻重置
*/
suspend fun resetImmediately() {
offsetX.snapTo(0F)
offsetY.snapTo(0F)
scale.snapTo(1F)
}
companion object {
val Saver: Saver = mapSaver(
save = {
mapOf(
it::offsetX.name to it.offsetX.value,
it::offsetY.name to it.offsetY.value,
it::scale.name to it.scale.value,
)
},
restore = {
val contentState = TransformContentState(itemStateMap = mutableMapOf())
val viewerContainerState = ViewerContainerState(transformState = contentState)
viewerContainerState.offsetX =
Animatable(it[viewerContainerState::offsetX.name] as Float)
viewerContainerState.offsetY =
Animatable(it[viewerContainerState::offsetY.name] as Float)
viewerContainerState.scale =
Animatable(it[viewerContainerState::scale.name] as Float)
viewerContainerState
}
)
}
}
/**
* 记录Viewer容器的状态
* @return ViewerContainerState
*/
@Deprecated(
message = commonDeprecatedText,
)
@Composable
internal fun rememberViewerContainerState(
// 协程作用域
scope: CoroutineScope = rememberCoroutineScope(),
// viewer状态
viewerState: ImageViewerState = rememberViewerState(),
// 转换content的state
transformContentState: TransformContentState = rememberTransformContentState(),
// 动画窗格
animationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
): ViewerContainerState {
val itemStateMap = LocalTransformItemStateMap.current
val transformState = TransformContentState(itemStateMap = itemStateMap)
val viewerContainerState = rememberSaveable(saver = ViewerContainerState.Saver) {
ViewerContainerState(transformState = transformState)
}
viewerContainerState.scope = scope
viewerContainerState.imageViewerState = viewerState
viewerContainerState.transformState = transformContentState
viewerContainerState.defaultAnimationSpec = animationSpec
return viewerContainerState
}
/**
* Viewer容器
*/
@Deprecated(
message = commonDeprecatedText,
)
@Composable
internal fun ImageViewerContainer(
// 修改对象
modifier: Modifier = Modifier,
// 容器状态
containerState: ViewerContainerState,
// 未加载成功时的占位
placeholder: PreviewerPlaceholder = PreviewerPlaceholder(),
// viewer主体
viewer: @Composable () -> Unit,
) {
containerState.apply {
Box(
modifier = modifier
.fillMaxSize()
.onGloballyPositioned {
containerSize = it.size
}
.graphicsLayer {
scaleX = scale.value
scaleY = scale.value
translationX = offsetX.value
translationY = offsetY.value
}
) {
// 支持转换效果的图层
Box(
modifier = Modifier
.fillMaxSize()
.alpha(transformContentAlpha.value)
) {
TransformContentView(transformState)
}
// viewer图层
Box(
modifier = Modifier
.fillMaxSize()
.alpha(viewerContainerAlpha.value)
) {
viewer()
}
// 判断viewer是否加载成功
val viewerMounted by imageViewerState.mountedFlow.collectAsState(
initial = false
)
if (allowLoading) AnimatedVisibility(
visible = !viewerMounted,
enter = placeholder.enterTransition,
exit = placeholder.exitTransition,
) {
placeholder.content()
}
}
}
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/previewer/PreviewerPagerState.kt
================================================
package com.origeek.imageViewer.previewer
import androidx.annotation.FloatRange
import androidx.annotation.IntRange
import com.origeek.imageViewer.gallery.ImageGalleryState
import com.origeek.imageViewer.viewer.commonDeprecatedText
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-10-17 14:41
**/
@Deprecated(
message = commonDeprecatedText,
)
open class PreviewerPagerState(
val galleryState: ImageGalleryState,
) {
/**
* 当前页码
*/
val currentPage: Int
get() = galleryState.currentPage
/**
* 目标页码
*/
val targetPage: Int
get() = galleryState.targetPage
/**
* 滚动到指定页面
* @param page Int
* @param pageOffset Float
*/
suspend fun scrollToPage(
@IntRange(from = 0) page: Int,
@FloatRange(from = 0.0, to = 1.0) pageOffset: Float = 0F,
) = galleryState.scrollToPage(page, pageOffset)
/**
* 带动画滚动到指定页面
* @param page Int
* @param pageOffset Float
*/
suspend fun animateScrollToPage(
@IntRange(from = 0) page: Int,
@FloatRange(from = 0.0, to = 1.0) pageOffset: Float = 0F,
) = galleryState.animateScrollToPage(page, pageOffset)
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/previewer/PreviewerTransformState.kt
================================================
package com.origeek.imageViewer.previewer
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.tween
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_SOFT_ANIMATION_SPEC
import com.jvziyaoyao.scale.zoomable.previewer.ItemStateMap
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemState
import com.origeek.imageViewer.gallery.ImageGalleryState
import com.origeek.imageViewer.util.Ticket
import com.origeek.imageViewer.viewer.ImageViewerState
import com.origeek.imageViewer.viewer.commonDeprecatedText
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-10-17 14:41
**/
@Deprecated(
message = commonDeprecatedText,
)
open class PreviewerTransformState(
// 协程作用域/
var scope: CoroutineScope = MainScope(),
// 默认动画窗格
var defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
// 预览状态
galleryState: ImageGalleryState,
// 用于获取TransformItemState
var itemStateMap: ItemStateMap,
) : PreviewerPagerState(
galleryState = galleryState,
) {
/**
* +-------------------+
* PRIVATE
* +-------------------+
*/
// 锁对象
private var mutex = Mutex()
// 打开回调,最外层animateVisible修改时调用
private var openCallback: (() -> Unit)? = null
// 关闭回调,最外层animateVisible修改时调用
private var closeCallback: (() -> Unit)? = null
// 是否显示viewer容器的标识
private val viewerContainerVisible: Boolean
get() = viewerContainerState?.viewerContainerAlpha?.value == 1F
/**
* 更新当前的标记状态
* @param animating Boolean
* @param visible Boolean
* @param visibleTarget Boolean?
*/
private suspend fun updateState(animating: Boolean, visible: Boolean, visibleTarget: Boolean?) {
mutex.withLock {
this.animating = animating
this.visible = visible
this.visibleTarget = visibleTarget
}
}
/**
* +-------------------+
* INTERNAL
* +-------------------+
*/
// 等待界面刷新的ticket
internal val ticket = Ticket()
// 最外侧animateVisibleState
internal var animateContainerVisibleState by mutableStateOf(MutableTransitionState(false))
// UI透明度
internal var uiAlpha = Animatable(0F)
// viewer透明度
internal var viewerAlpha = Animatable(1F)
// 从外部传入viewer容器
internal var viewerContainerState by mutableStateOf(null)
// 从外部提供transformContentState
internal val transformState: TransformContentState?
get() = viewerContainerState?.transformState
// 进入转换动画
internal var enterTransition: EnterTransition? = null
// 离开的转换动画
internal var exitTransition: ExitTransition? = null
// 判断是否允许transform结束
internal val canTransformOut: Boolean
get() = (viewerContainerState?.openTransformJob != null) || (imageViewerState?.mountedFlow?.value == true)
// 标记打开动作,执行开始
internal suspend fun stateOpenStart() =
updateState(animating = true, visible = false, visibleTarget = true)
// 标记打开动作,执行结束
internal suspend fun stateOpenEnd() =
updateState(animating = false, visible = true, visibleTarget = null)
// 标记关闭动作,执行开始
internal suspend fun stateCloseStart() =
updateState(animating = true, visible = true, visibleTarget = false)
// 标记关闭动作,执行结束
internal suspend fun stateCloseEnd() =
updateState(animating = false, visible = false, visibleTarget = null)
/**
* 转换图层转viewer图层,true显示viewer,false显示转换图层
* @param isViewer Boolean
*/
internal suspend fun transformSnapToViewer(isViewer: Boolean) {
if (isViewer && visibleTarget == false) return
viewerContainerState?.transformSnapToViewer(isViewer)
}
/**
* animateVisable执行完成后调用回调方法
*/
internal fun onAnimateContainerStateChanged() {
if (animateContainerVisibleState.currentState) {
openCallback?.invoke()
transformState?.setEnterState()
} else {
closeCallback?.invoke()
}
}
/**
* +-------------------+
* PUBLIC
* +-------------------+
*/
// 是否正在进行动画
var animating by mutableStateOf(false)
internal set
// 是否可见
var visible by mutableStateOf(false)
internal set
// 是否可见的目标值
var visibleTarget by mutableStateOf(null)
internal set
// 是否允许执行open操作
val canOpen: Boolean
get() = !visible && visibleTarget == null && !animating
// 是否允许执行close操作
val canClose: Boolean
get() = visible && visibleTarget == null && !animating
// imageViewer状态对象
val imageViewerState: ImageViewerState?
get() = viewerContainerState?.imageViewerState
/**
* 根据页面获取当前页码所属的key
*/
var getKey: ((Int) -> Any)? = null
// 查找key关联的transformItem
fun findTransformItem(key: Any): TransformItemState? {
return itemStateMap[key]
}
// 根据index查询key
fun findTransformItemByIndex(index: Int): TransformItemState? {
val key = getKey?.invoke(index) ?: return null
return findTransformItem(key)
}
// 清除全部transformItems
fun clearTransformItems() = itemStateMap.clear()
/**
* 打开previewer
* @param index Int
* @param itemState TransformItemState?
* @param enterTransition EnterTransition?
*/
suspend fun open(
index: Int = 0,
itemState: TransformItemState? = null,
enterTransition: EnterTransition? = null
) =
suspendCoroutine { c ->
// 设置当前转换动画
this.enterTransition = enterTransition
// 设置转换回调
openCallback = {
c.resume(Unit)
// 清除转换回调
openCallback = null
// 清除转换动画
this.enterTransition = null
// 标记结束
scope.launch {
stateOpenEnd()
}
}
scope.launch {
// 标记开始
stateOpenStart()
// 开启UI
uiAlpha.snapTo(1F)
// container动画立即设置为关闭
animateContainerVisibleState = MutableTransitionState(false)
// 开启container
animateContainerVisibleState.targetState = true
// 跳转到index
galleryState.scrollToPage(index)
// 等待下一帧之后viewerContainerState才会刷新出来
ticket.awaitNextTicket()
// 允许显示loading
viewerContainerState?.allowLoading = true
// 开启viewer
viewerContainerState?.viewerContainerAlpha?.snapTo(1F)
// 如果输入itemState,则用itemState做为背景
if (itemState != null) {
scope.launch {
viewerContainerState?.transformContentAlpha?.snapTo(1F)
transformState?.awaitContainerSizeSpecifier()
transformState?.enterTransform(itemState, tween(0))
}
}
// 这里需要等待viewer挂载,显示loading界面
viewerContainerState?.awaitOpenTransform()
}
}
/**
* 关闭previewer
* @param exitTransition ExitTransition?
*/
suspend fun close(exitTransition: ExitTransition? = null) = suspendCoroutine { c ->
// 设置当前退出动画
this.exitTransition = exitTransition
// 设置退出结束的回调方法
closeCallback = {
c.resume(Unit)
// 将回调设置为空
closeCallback = null
// 将退出动画设置为空
this.exitTransition = null
// 标记结束
scope.launch {
stateCloseEnd()
}
}
scope.launch {
// 标记开始
stateCloseStart()
// 关闭正在进行的开启操作
viewerContainerState?.cancelOpenTransform()
// 这里创建一个全新的state是为了让exitTransition的设置得到响应
animateContainerVisibleState = MutableTransitionState(true)
// 开启container关闭动画
animateContainerVisibleState.targetState = false
// 等待下一帧
ticket.awaitNextTicket()
// transformState标记退出
transformState?.setExitState()
}
}
/**
* 打开previewer,带转换效果
* @param index Int
* @param itemState TransformItemState
* @param animationSpec AnimationSpec?
*/
suspend fun openTransform(
index: Int,
itemState: TransformItemState? = findTransformItemByIndex(index),
animationSpec: AnimationSpec = defaultAnimationSpec
) {
// 如果itemState为空,改用open的方式打开
if (itemState == null) {
open(index)
return
}
// 动画开始
stateOpenStart()
// 关闭UI
uiAlpha.snapTo(0F)
// 关闭viewer
viewerAlpha.snapTo(0F)
// 设置新的container状态立刻设置为true
animateContainerVisibleState = MutableTransitionState(true)
// 跳转到index页
galleryState.scrollToPage(index)
// 等待下一帧
ticket.awaitNextTicket()
// 关闭loading
viewerContainerState?.allowLoading = false
// 关闭viewer。打开transform
transformSnapToViewer(false)
// 开启viewer
viewerAlpha.snapTo(1F)
// 这两个一起执行
listOf(
scope.async {
// 开启动画
transformState?.enterTransform(itemState, animationSpec)
// 开启loading
viewerContainerState?.allowLoading = true
},
scope.async {
// UI慢慢显示
uiAlpha.animateTo(1F, animationSpec)
}
).awaitAll()
// 执行完成后的回调
stateOpenEnd()
// 这里需要等待viewer挂载,显示loading界面
viewerContainerState?.awaitOpenTransform()
}
/**
* 关闭previewer,带转换效果
* @param key Any
* @param animationSpec AnimationSpec?
*/
suspend fun closeTransform(
animationSpec: AnimationSpec = defaultAnimationSpec,
) {
// 标记开始
stateCloseStart()
// 判断当前状态是否允许transform结束
// 需要在cancel前获取该值
val canNowTransformOut = canTransformOut
// 关闭可能正在进行的open操作
viewerContainerState?.cancelOpenTransform()
// 关闭loading的显示
viewerContainerState?.allowLoading = false
// 查询item是否存在
val itemState = findTransformItemByIndex(currentPage)
// 如果存在,就transform退出,否则就普通退出
if (itemState != null && canNowTransformOut) {
// 如果viewer在显示的状态,退出时将viewer的pose复制给content
if (viewerContainerVisible) {
// 标记transform的开始状态,否则copy无效
transformState?.setEnterState()
// 更新transformState
transformState?.notifyEnterChanged()
// 等待刷新完毕
ticket.awaitNextTicket()
// 复制viewer的pos给transform
viewerContainerState?.copyViewerPosToContent(itemState)
// 切换为transform
transformSnapToViewer(false)
}
// 等待下一帧
ticket.awaitNextTicket()
listOf(
scope.async {
// transform动画退出
transformState?.exitTransform(animationSpec)
// 退出结束后隐藏content
viewerContainerState?.transformContentAlpha?.snapTo(0F)
},
scope.async {
// 动画隐藏UI
uiAlpha.animateTo(0F, animationSpec)
}
).awaitAll()
// 等待下一帧
ticket.awaitNextTicket()
// 彻底关闭container
animateContainerVisibleState = MutableTransitionState(false)
} else {
// transform标记退出
transformState?.setExitState()
// container动画退出
animateContainerVisibleState.targetState = false
}
// 允许使用loading
viewerContainerState?.allowLoading = true
// 标记结束;
stateCloseEnd()
}
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/previewer/PreviewerVerticalDragState.kt
================================================
package com.origeek.imageViewer.previewer
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerInputScope
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_SCALE_TO_CLOSE_MIN_VALUE
import com.jvziyaoyao.scale.zoomable.previewer.DEFAULT_SOFT_ANIMATION_SPEC
import com.jvziyaoyao.scale.zoomable.previewer.ItemStateMap
import com.jvziyaoyao.scale.zoomable.previewer.TransformItemState
import com.jvziyaoyao.scale.zoomable.previewer.VerticalDragType
import com.origeek.imageViewer.gallery.ImageGalleryState
import com.origeek.imageViewer.viewer.commonDeprecatedText
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-10-17 14:42
**/
/**
* 增加垂直方向拖拽的能力
*/
@Deprecated(
message = commonDeprecatedText,
)
open class PreviewerVerticalDragState(
// 协程作用域
scope: CoroutineScope = MainScope(),
// 默认动画窗格
defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
// 开启垂直手势的类型
verticalDragType: VerticalDragType = VerticalDragType.None,
// 下拉关闭的缩小的阈值
scaleToCloseMinValue: Float = DEFAULT_SCALE_TO_CLOSE_MIN_VALUE,
// 预览状态
galleryState: ImageGalleryState,
// 用于获取TransformItemState
itemStateMap: ItemStateMap,
) : PreviewerTransformState(scope, defaultAnimationSpec, galleryState, itemStateMap) {
/**
* viewer容器缩小关闭
*/
private suspend fun viewerContainerShrinkDown() {
// 标记动作开始
stateCloseStart()
listOf(
// 缩小容器
scope.async {
viewerContainerState?.scale?.animateTo(0F, animationSpec = defaultAnimationSpec)
},
// 关闭UI
scope.async {
uiAlpha.animateTo(0F, animationSpec = defaultAnimationSpec)
}
).awaitAll()
// 等待下一帧
ticket.awaitNextTicket()
// 关闭动画组件
animateContainerVisibleState = MutableTransitionState(false)
// 等待下一帧
ticket.awaitNextTicket()
// 重置container
viewerContainerState?.reset(defaultAnimationSpec)
// 将transform标记为退出
transformState?.setExitState()
// 标记动作结束
stateCloseEnd()
}
/**
* 响应下拉关闭
*/
private suspend fun dragDownClose() {
// 刷新transform的pos
transformState?.notifyEnterChanged()
// 关闭loading
viewerContainerState?.allowLoading = false
// 等待下一帧,确保transform的pos刷新成功
ticket.awaitNextTicket()
// 将container的pos复制给transform
viewerContainerState?.copyViewerContainerStateToTransformState()
// container重置
viewerContainerState?.resetImmediately()
// 切换到transform
transformSnapToViewer(false)
// 等待下一帧
ticket.awaitNextTicket()
// 执行转换关闭
closeTransform(defaultAnimationSpec)
// 解除loading限制
viewerContainerState?.allowLoading = true
}
/**
* 设置下拉手势的方法
* @param pointerInputScope PointerInputScope
*/
internal suspend fun verticalDrag(pointerInputScope: PointerInputScope) {
pointerInputScope.apply {
// 记录开始时的位置
var vStartOffset by mutableStateOf(null)
// 标记是否为下拉关闭
var vOrientationDown by mutableStateOf(null)
// 如果getKay不为空才开始检测手势
if (verticalDragType != VerticalDragType.None) detectVerticalDragGestures(
onDragStart = OnDragStart@{
// 如果imageViewerState不存在,无法进行下拉手势
if (imageViewerState == null) return@OnDragStart
var transformItemState: TransformItemState? = null
// 查询当前transformItem
getKey?.apply {
findTransformItem(invoke(currentPage))?.apply {
transformItemState = this
}
}
// 判断是否允许变换退出,如果允许就标记动作开始
// setExitState后,在下拉过程中,itemState不会从界面上消失
if (canTransformOut) {
transformState?.setEnterState()
} else {
transformState?.setExitState()
}
// 更新当前transformItem
transformState?.itemState = transformItemState
// 只有viewer的缩放率为1时才允许下拉手势
if (imageViewerState?.scale?.value == 1F) {
vStartOffset = it
// 进入下拉手势时禁用viewer的手势
imageViewerState?.allowGestureInput = false
}
},
onDragEnd = OnDragEnd@{
// 如果开始位置为空,就退出
if (vStartOffset == null) return@OnDragEnd
// 如果containerState为空,就退出
if (viewerContainerState == null) return@OnDragEnd
// 重置开始位置和方向
vStartOffset = null
vOrientationDown = null
// 解除viewer的手势输入限制
imageViewerState?.allowGestureInput = true
// 缩放小于阈值,执行关闭动画,大于就恢复原样
if (viewerContainerState!!.scale.value < scaleToCloseMinValue) {
scope.launch {
if (getKey != null && canTransformOut) {
val key = getKey!!.invoke(currentPage)
val transformItem = findTransformItem(key)
// 如果item在画面内,就执行变换关闭,否则缩小关闭
if (transformItem != null) {
dragDownClose()
} else {
viewerContainerShrinkDown()
}
} else {
viewerContainerShrinkDown()
}
// 结束动画后需要把关闭的UI打开
uiAlpha.snapTo(1F)
}
} else {
scope.launch {
uiAlpha.animateTo(1F, defaultAnimationSpec)
}
scope.launch {
viewerContainerState?.reset(defaultAnimationSpec)
}
}
},
onVerticalDrag = OnVerticalDrag@{ change, dragAmount ->
if (imageViewerState == null) return@OnVerticalDrag
if (viewerContainerState == null) return@OnVerticalDrag
if (vStartOffset == null) return@OnVerticalDrag
if (vOrientationDown == null) vOrientationDown = dragAmount > 0
if (vOrientationDown == true || verticalDragType == VerticalDragType.UpAndDown) {
val offsetY = change.position.y - vStartOffset!!.y
val offsetX = change.position.x - vStartOffset!!.x
val containerHeight = viewerContainerState!!.containerSize.height
val scale = (containerHeight - offsetY.absoluteValue).div(
containerHeight
)
scope.launch {
uiAlpha.snapTo(scale)
viewerContainerState?.offsetX?.snapTo(offsetX)
viewerContainerState?.offsetY?.snapTo(offsetY)
viewerContainerState?.scale?.snapTo(scale)
}
} else {
// 如果不是向上,就返还输入权,以免页面卡顿
imageViewerState?.allowGestureInput = true
}
}
)
}
}
/**
* 开启垂直手势的类型
*/
var verticalDragType by mutableStateOf(verticalDragType)
/**
* 下拉关闭的缩放的阈值,当scale小于这个值,就关闭,否则还原
*/
var scaleToCloseMinValue by mutableStateOf(scaleToCloseMinValue)
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/util/Ticket.kt
================================================
package com.origeek.imageViewer.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.origeek.imageViewer.viewer.commonDeprecatedText
import java.util.UUID
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-05-24 12:15
**/
@Deprecated(
message = commonDeprecatedText,
)
class Ticket {
private var ticket by mutableStateOf("")
private val ticketMap = mutableMapOf>()
suspend fun awaitNextTicket() = suspendCoroutine { c ->
ticket = UUID.randomUUID().toString()
ticketMap[ticket] = c
}
private fun clearTicket() {
ticketMap.forEach {
it.value.resume(Unit)
ticketMap.remove(it.key)
}
}
@Composable
fun Next() {
LaunchedEffect(ticket) {
clearTicket()
}
}
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/viewer/ImageComposeCanvas.kt
================================================
package com.origeek.imageViewer.viewer
import android.graphics.Bitmap
import android.graphics.Rect
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import com.jvziyaoyao.scale.image.sampling.SamplingDecoder
import com.jvziyaoyao.scale.image.sampling.RenderBlock
import com.jvziyaoyao.scale.image.sampling.calculateInSampleSize
import com.jvziyaoyao.scale.image.sampling.checkRectInBound
import com.origeek.imageViewer.previewer.DEFAULT_CROSS_FADE_ANIMATE_SPEC
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.math.absoluteValue
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun ImageComposeCanvas(
modifier: Modifier = Modifier,
samplingDecoder: SamplingDecoder,
scale: Float = DEFAULT_SCALE,
offsetX: Float = DEFAULT_OFFSET_X,
offsetY: Float = DEFAULT_OFFSET_Y,
rotation: Float = DEFAULT_ROTATION,
gesture: RawGesture = RawGesture(),
onMounted: () -> Unit = {},
onSizeChange: suspend (SizeChangeContent) -> Unit = {},
crossfadeAnimationSpec: AnimationSpec = DEFAULT_CROSS_FADE_ANIMATE_SPEC,
boundClip: Boolean = true,
debugMode: Boolean = false,
) {
val scope = rememberCoroutineScope()
// 容器大小
var bSize by remember { mutableStateOf(IntSize.Zero) }
// 容器长宽比
val bRatio by remember { derivedStateOf { bSize.width.toFloat() / bSize.height.toFloat() } }
// 原图长宽比
val oRatio by remember { derivedStateOf { samplingDecoder.decoderWidth.toFloat() / samplingDecoder.decoderHeight.toFloat() } }
// 是否宽度与容器大小一致
var widthFixed by remember { mutableStateOf(false) }
// 长宽是否均超出容器长宽
val superSize by remember {
derivedStateOf {
samplingDecoder.decoderHeight > bSize.height && samplingDecoder.decoderWidth > bSize.width
}
}
// 显示的默认大小
val uSize by remember {
derivedStateOf {
if (oRatio > bRatio) {
// 宽度一致
val uW = bSize.width
val uH = uW / oRatio
widthFixed = true
IntSize(uW, uH.toInt())
} else {
// 高度一致
val uH = bSize.height
val uW = uH * oRatio
widthFixed = false
IntSize(uW.toInt(), uH)
}
}
}
// 显示的实际大小
val rSize by remember(key1 = scale) {
derivedStateOf {
IntSize(
(uSize.width * scale).toInt(),
(uSize.height * scale).toInt()
)
}
}
// 同时监听容器和实际图片大小的变化
LaunchedEffect(key1 = bSize, key2 = rSize) {
// 获取最大缩放率
val maxScale = when {
superSize -> {
samplingDecoder.decoderWidth.toFloat() / uSize.width.toFloat()
}
widthFixed -> {
bSize.height.toFloat() / uSize.height.toFloat()
}
else -> {
bSize.width.toFloat() / uSize.width.toFloat()
}
}
// 回调
onSizeChange(
SizeChangeContent(
defaultSize = uSize,
containerSize = bSize,
maxScale = maxScale
)
)
}
// 判断是否需要高画质渲染
val needRenderHeightTexture by remember(key1 = bSize) {
derivedStateOf {
// 目前策略:原图的面积大于容器面积,就要渲染高画质
BigDecimal(samplingDecoder.decoderWidth)
.multiply(BigDecimal(samplingDecoder.decoderHeight)) > BigDecimal(bSize.height)
.multiply(BigDecimal(bSize.width))
}
}
// 标识当前是否开启高画质渲染,如果需要高画质渲染,并且缩放大于1
val renderHeightTexture by remember(key1 = scale) { derivedStateOf { needRenderHeightTexture && scale > 1 } }
// 当前采样率
var inSampleSize by remember { mutableStateOf(1) }
// 最小图的采样率
var zeroInSampleSize by remember { mutableStateOf(8) }
// 底图的采样率
var backGroundInSample by remember { mutableStateOf(0) }
// 底图bitmap
var bitmap by remember { mutableStateOf(null) }
// 监听渲染实际大小,动态修改图片的采样率
LaunchedEffect(key1 = rSize) {
if (scale < 1F) return@LaunchedEffect
inSampleSize = calculateInSampleSize(
srcWidth = samplingDecoder.decoderWidth,
reqWidth = rSize.width
)
if (scale == 1F) {
zeroInSampleSize = inSampleSize
}
}
// 根据采样率变化,实时更新底图
LaunchedEffect(key1 = zeroInSampleSize, key2 = inSampleSize, key3 = needRenderHeightTexture) {
scope.launch(Dispatchers.IO) {
// 如果不需要渲染高画质,就不需要分块渲染,直接使用当前采样率,用底图来展示
val iss = if (needRenderHeightTexture) zeroInSampleSize else inSampleSize
if (iss == backGroundInSample) return@launch
backGroundInSample = iss
bitmap = samplingDecoder.decodeRegion(
iss, Rect(
0,
0,
samplingDecoder.decoderWidth,
samplingDecoder.decoderHeight
)
)
}
}
DisposableEffect(Unit) {
onDispose {
bitmap?.recycle()
bitmap = null
}
}
// 底图偏移量X,要确保图片在容器中居中对齐
val deltaX by remember(key1 = offsetX, key2 = bSize, key3 = rSize) {
derivedStateOf {
offsetX + (bSize.width - rSize.width).toFloat().div(2)
}
}
// 底图偏移量Y,要确保图片在容器中居中对齐
val deltaY by remember(key1 = offsetY, key2 = bSize, key3 = rSize) {
derivedStateOf {
offsetY + (bSize.height - rSize.height).toFloat().div(2)
}
}
// 计算显示区域内矩形的宽度
val rectW by remember(key1 = offsetX) {
derivedStateOf {
calcLeftSize(
bSize = bSize.width.toFloat(),
rSize = rSize.width.toFloat(),
offset = offsetX,
)
}
}
// 计算显示区域内矩形的高度
val rectH by remember(key1 = offsetY, key2 = rSize) {
derivedStateOf {
calcLeftSize(
bSize = bSize.height.toFloat(),
rSize = rSize.height.toFloat(),
offset = offsetY,
)
}
}
// 渲染可见区域的开始坐标X
val stX by remember(key1 = offsetX) {
derivedStateOf {
// 计算显示区域矩形的偏移坐标
val rectDeltaX = getRectDelta(
deltaX,
rSize.width.toFloat(),
bSize.width.toFloat(),
offsetX
)
// 偏移坐标减偏移量求出矩形在图片上的相对坐标
rectDeltaX - deltaX
}
}
// 渲染可见区域的开始坐标Y
val stY by remember(key1 = offsetY) {
derivedStateOf {
// 计算显示区域矩形的偏移坐标
val rectDeltaY = getRectDelta(
deltaY,
rSize.height.toFloat(),
bSize.height.toFloat(),
offsetY
)
// 偏移坐标减偏移量求出矩形在图片上的相对坐标
rectDeltaY - deltaY
}
}
// 开始坐标加上宽度等于结束坐标
val edX by remember(key1 = offsetX) { derivedStateOf { stX + rectW } }
// 开始坐标加上高度等于结束坐标
val edY by remember(key1 = offsetY) { derivedStateOf { stY + rectH } }
// 更新时间戳,用于通知canvas更新方块
var renderUpdateTimeStamp by remember { mutableStateOf(0L) }
// 开启解码队列的循环
LaunchedEffect(key1 = Unit) {
samplingDecoder.startRenderQueue {
// 解码器解码一个,就更新一次时间戳
renderUpdateTimeStamp = System.currentTimeMillis()
}
}
// 切换到不需要高画质渲染时,需要清除解码队列,清除全部的bitmap
LaunchedEffect(key1 = renderHeightTexture) {
if (!renderHeightTexture) {
samplingDecoder.renderQueue.clear()
samplingDecoder.clearAllBitmap()
}
}
/**
* 更新渲染队列
*/
var calcMaxCountPending by remember { mutableStateOf(false) }
// 先前的缩放比
var previousScale by remember { mutableStateOf(null) }
// 先前的偏移量
var previousOffset by remember { mutableStateOf(null) }
// 记录最长边的最大方块数
var blockDividerCount by remember { mutableStateOf(1) }
// 用来标识这个参数是否有改变
var preBlockDividerCount by remember { mutableStateOf(blockDividerCount) }
// 更新渲染方块的信息
fun updateRenderList() {
// 如果此时正在重新计算渲染方块的数目,就退出
if (calcMaxCountPending) return
// 更新的时候如果缩放和偏移量没有变化,方块数量也没变,就没有必要计算了
if (
previousOffset?.x == offsetX
&& previousOffset?.y == offsetY
&& previousScale == scale
&& preBlockDividerCount == blockDividerCount
) return
previousScale = scale
previousOffset = Offset(offsetX, offsetY)
// 计算当前渲染方块大小
val renderBlockSize =
samplingDecoder.blockSize * (rSize.width.toFloat().div(samplingDecoder.decoderWidth))
var tlx: Int
var tly: Int
var startX: Float
var startY: Float
var endX: Float
var endY: Float
var eh: Int
var ew: Int
var needUpdate: Boolean
var previousInBound: Boolean
var previousInSampleSize: Int
var lastX: Int?
var lastY: Int? = null
var lastXDelta: Int
var lastYDelta: Int
val insertList = ArrayList()
val removeList = ArrayList()
for ((column, list) in samplingDecoder.renderList.withIndex()) {
startY = column * renderBlockSize
endY = (column + 1) * renderBlockSize
tly = (deltaY + startY).toInt()
eh = (if (endY > rSize.height) rSize.height - startY else renderBlockSize).toInt()
// 由于计算的精度问题,需要确保每一个区块都要严丝合缝
lastY?.let {
if (it < tly) {
lastYDelta = tly - it
tly = it
eh += lastYDelta
}
}
lastY = tly + eh
lastX = null
for ((row, block) in list.withIndex()) {
startX = row * renderBlockSize
tlx = (deltaX + startX).toInt()
endX = (row + 1) * renderBlockSize
ew = (if (endX > rSize.width) rSize.width - startX else renderBlockSize).toInt()
previousInSampleSize = block.inSampleSize
previousInBound = block.inBound
// 记录当前区块的采用率
block.inSampleSize = inSampleSize
// 判断区块是否在可视范围内
block.inBound = checkRectInBound(
startX, startY, endX, endY,
stX, stY, edX, edY
)
// 由于计算的精度问题,需要确保每一个区块都要严丝合缝
lastX?.let {
if (it < tlx) {
lastXDelta = tlx - it
tlx = it
ew += lastXDelta
}
}
lastX = tlx + ew
// 记录区块的实际偏移量
block.renderOffset = IntOffset(tlx, tly)
// 记录区块的实际大小
block.renderSize = IntSize(
width = ew,
height = eh,
)
// 如果参数跟之前的一样,就没有必要更新bitmap
needUpdate = previousInBound != block.inBound
|| previousInSampleSize != block.inSampleSize
if (!needUpdate) continue
if (!renderHeightTexture) continue
// 解码队列操作时是有锁的,会对性能造成影响
if (block.inBound) {
if (!samplingDecoder.renderQueue.contains(block)) {
insertList.add(block)
}
} else {
removeList.add(block)
block.release()
}
}
}
scope.launch(Dispatchers.IO) {
synchronized(samplingDecoder.renderQueue) {
insertList.forEach {
samplingDecoder.renderQueue.putFirst(it)
}
removeList.forEach {
samplingDecoder.renderQueue.remove(it)
}
}
}
}
LaunchedEffect(key1 = rSize, key2 = rectW, key3 = rectH) {
// 可视区域面积
val rectArea = BigDecimal(rectW.toDouble()).multiply(BigDecimal(rectH.toDouble()))
// 实际大小面积
val realArea = BigDecimal(rSize.width).multiply(BigDecimal(rSize.height))
// 被除数不能为0
if (realArea.toFloat() == 0F) return@LaunchedEffect
// 计算实际面积的可视率
val renderAreaPercentage =
rectArea.divide(realArea, 2, RoundingMode.HALF_EVEN).toFloat()
// 根据不同可视率,匹配合适的方块数,最大只能到8
val goBlockDividerCount = when {
renderAreaPercentage > 0.6F -> 1
renderAreaPercentage > 0.025F -> 4
else -> 8
}
// 如果没变,就不要修改
if (goBlockDividerCount == blockDividerCount) return@LaunchedEffect
preBlockDividerCount = blockDividerCount
blockDividerCount = goBlockDividerCount
scope.launch(Dispatchers.IO) {
// 清空解码队列
samplingDecoder.renderQueue.clear()
// 进入修改区间
calcMaxCountPending = true
samplingDecoder.setMaxBlockCount(blockDividerCount)
calcMaxCountPending = false
// 离开修改区间
// 更新一下界面
updateRenderList()
}
}
// 旋转中心
val rotationCenter by remember(key1 = offsetX, key2 = offsetY, key3 = scale) {
derivedStateOf {
val cx = deltaX + rSize.width.div(2)
val cy = deltaY + rSize.height.div(2)
Offset(cx, cy)
}
}
/**
* canvas加载成功后避免闪一下
*/
val canvasAlpha = remember { Animatable(0F) }
LaunchedEffect(key1 = bitmap) {
if (bitmap != null && bitmap!!.width > 1 && bitmap!!.height > 1) {
if (canvasAlpha.value == 0F) {
scope.launch {
canvasAlpha.animateTo(
targetValue = 1F,
animationSpec = crossfadeAnimationSpec
)
onMounted()
}
}
}
}
Canvas(
modifier = modifier
.alpha(canvasAlpha.value)
.fillMaxSize()
.graphicsLayer {
// 图片位移时会超出容器大小,需要在这个地方指定是否裁切
clip = boundClip
}
.onSizeChanged {
bSize = it
}
.pointerInput(Unit) {
detectTapGestures(onLongPress = gesture.onLongPress)
}
.pointerInput(Unit) {
detectTransformGestures(
onTap = gesture.onTap,
onDoubleTap = gesture.onDoubleTap,
gestureStart = gesture.gestureStart,
gestureEnd = gesture.gestureEnd,
onGesture = gesture.onGesture,
)
},
) {
withTransform({
rotate(degrees = rotation, pivot = rotationCenter)
}) {
if (bitmap != null) {
drawImage(
image = bitmap!!.asImageBitmap(),
dstSize = IntSize(rSize.width, rSize.height),
dstOffset = IntOffset(deltaX.toInt(), deltaY.toInt()),
)
}
// 更新渲染队列
if (renderUpdateTimeStamp >= 0) updateRenderList()
if (renderHeightTexture && !calcMaxCountPending) {
samplingDecoder.forEachBlock { block, _, _ ->
block.getBitmap()?.let {
drawImage(
image = it.asImageBitmap(),
dstSize = block.renderSize,
dstOffset = block.renderOffset
)
}
}
}
// 这里会把可视区域的矩形画出来
if (debugMode) {
drawRect(
color = Color.Blue.copy(0.1F),
topLeft = Offset(deltaX + stX, deltaY + stY),
size = Size(rectW, rectH)
)
}
}
}
}
fun getRectDelta(delta: Float, rSize: Float, bSize: Float, offset: Float): Float {
return delta + if (delta < 0) {
val direction = if (rSize > bSize) -1 else 1
(offset + (direction) * (bSize - rSize)
.div(2).absoluteValue).absoluteValue
} else 0F
}
fun calcLeftSize(bSize: Float, rSize: Float, offset: Float): Float {
return if (offset.absoluteValue > (bSize - rSize).div(2).absoluteValue) {
rSize - (offset.absoluteValue - (bSize - rSize).div(2))
} else {
rSize.coerceAtMost(bSize)
}
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/viewer/ImageComposeOrigin.kt
================================================
package com.origeek.imageViewer.viewer
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntSize
import com.origeek.imageViewer.previewer.DEFAULT_CROSS_FADE_ANIMATE_SPEC
import kotlinx.coroutines.launch
@Deprecated(
message = commonDeprecatedText,
)
class RawGesture(
val onTap: (Offset) -> Unit = {},
val onDoubleTap: (Offset) -> Unit = {},
val onLongPress: (Offset) -> Unit = {},
val gestureStart: () -> Unit = {},
val gestureEnd: (transformOnly: Boolean) -> Unit = {},
val onGesture: (centroid: Offset, pan: Offset, zoom: Float, rotation: Float, event: PointerEvent) -> Boolean = { _, _, _, _, _ -> true },
)
@Deprecated(
message = commonDeprecatedText,
)
data class SizeChangeContent(
val defaultSize: IntSize,
val containerSize: IntSize,
val maxScale: Float,
)
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun ImageComposeOrigin(
modifier: Modifier = Modifier,
model: Any,
scale: Float = DEFAULT_SCALE,
offsetX: Float = DEFAULT_OFFSET_X,
offsetY: Float = DEFAULT_OFFSET_Y,
rotation: Float = DEFAULT_ROTATION,
gesture: RawGesture = RawGesture(),
onMounted: () -> Unit = {},
onSizeChange: suspend (SizeChangeContent) -> Unit = {},
crossfadeAnimationSpec: AnimationSpec = DEFAULT_CROSS_FADE_ANIMATE_SPEC,
boundClip: Boolean = true,
) {
val scope = rememberCoroutineScope()
// 容器大小
var bSize by remember { mutableStateOf(IntSize(0, 0)) }
// 容器比例
val bRatio by remember { derivedStateOf { bSize.width.toFloat() / bSize.height.toFloat() } }
// 图片原始大小
var oSize by remember { mutableStateOf(IntSize(0, 0)) }
// 图片原始比例
val oRatio by remember { derivedStateOf { oSize.width.toFloat() / oSize.height.toFloat() } }
// 是否宽度与容器大小一致
var widthFixed by remember { mutableStateOf(false) }
// 长宽是否均超出容器长宽
val superSize by remember {
derivedStateOf {
oSize.height > bSize.height && oSize.width > bSize.width
}
}
// 显示大小
val uSize by remember {
derivedStateOf {
if (oRatio > bRatio) {
// 宽度一致
val uW = bSize.width
val uH = uW / oRatio
widthFixed = true
IntSize(uW, uH.toInt())
} else {
// 高度一致
val uH = bSize.height
val uW = uH * oRatio
widthFixed = false
IntSize(uW.toInt(), uH)
}
}
}
// 图片显示的真实大小
val rSize by remember {
derivedStateOf {
IntSize(
(uSize.width * scale).toInt(),
(uSize.height * scale).toInt()
)
}
}
LaunchedEffect(key1 = oSize, key2 = bSize, key3 = rSize) {
val maxScale = when {
superSize -> {
oSize.width.toFloat() / uSize.width.toFloat()
}
widthFixed -> {
bSize.height.toFloat() / uSize.height.toFloat()
}
else -> {
bSize.width.toFloat() / uSize.width.toFloat()
}
}
onSizeChange(
SizeChangeContent(
defaultSize = uSize,
containerSize = bSize,
maxScale = maxScale
)
)
}
// 图片是否加载成功
var imageSpecified by remember { mutableStateOf(false) }
// 承载容器的透明度,主要用来控制图片加载成功后的渐变效果
val viewerAlpha = remember { Animatable(0F) }
/**
* mounted回调
*/
fun goMounted() {
scope.launch {
viewerAlpha.animateTo(1F, crossfadeAnimationSpec)
onMounted()
}
}
when (model) {
is Painter -> {
var isMounted by remember { mutableStateOf(false) }
imageSpecified = model.intrinsicSize.isSpecified
LaunchedEffect(key1 = model.intrinsicSize, block = {
if (imageSpecified) {
oSize = IntSize(
model.intrinsicSize.width.toInt(),
model.intrinsicSize.height.toInt()
)
if (!isMounted) {
isMounted = true
goMounted()
}
}
})
}
is ImageVector -> {
imageSpecified = true
LocalDensity.current.run {
oSize = IntSize(
model.defaultWidth.toPx().toInt(),
model.defaultHeight.toPx().toInt(),
)
goMounted()
}
}
is ImageBitmap -> {
imageSpecified = true
oSize = IntSize(
model.width,
model.height
)
goMounted()
}
is ComposeModel -> {
imageSpecified = true
LaunchedEffect(key1 = model.intrinsicSize, block = {
oSize = if (model.intrinsicSize == IntSize.Zero) {
bSize
} else {
model.intrinsicSize
}
})
goMounted()
}
else -> throw Exception("This model type is not supported!")
}
Box(
modifier = modifier
.fillMaxSize()
.graphicsLayer {
// 图片位移时会超出容器大小,需要在这个地方指定是否裁切
clip = boundClip
alpha = viewerAlpha.value
}
.onSizeChanged {
bSize = it
}
.pointerInput(Unit) {
detectTapGestures(onLongPress = gesture.onLongPress)
}
.pointerInput(key1 = imageSpecified) {
if (imageSpecified) detectTransformGestures(
onTap = gesture.onTap,
onDoubleTap = gesture.onDoubleTap,
gestureStart = gesture.gestureStart,
gestureEnd = gesture.gestureEnd,
onGesture = gesture.onGesture,
)
},
contentAlignment = Alignment.Center,
) {
val imageModifier = Modifier
.graphicsLayer {
if (imageSpecified) {
scaleX = scale
scaleY = scale
translationX = offsetX
translationY = offsetY
rotationZ = rotation
}
}
.size(
LocalDensity.current.run { uSize.width.toDp() },
LocalDensity.current.run { uSize.height.toDp() }
)
when (model) {
is Painter -> {
Image(
painter = model,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = imageModifier,
)
}
is ImageVector -> {
Image(
imageVector = model,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = imageModifier,
)
}
is ImageBitmap -> {
Image(
bitmap = model,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = imageModifier,
)
}
is ComposeModel -> {
Box(modifier = imageModifier, contentAlignment = Alignment.Center) {
model.PoseContent()
}
}
}
}
}
================================================
FILE: scale-image-viewer-classic/src/main/java/com/origeek/imageViewer/viewer/ImageViewer.kt
================================================
package com.origeek.imageViewer.viewer
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.FloatExponentialDecaySpec
import androidx.compose.animation.core.SpringSpec
import androidx.compose.animation.core.generateDecayAnimationSpec
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.calculateCentroid
import androidx.compose.foundation.gestures.calculateCentroidSize
import androidx.compose.foundation.gestures.calculatePan
import androidx.compose.foundation.gestures.calculateRotation
import androidx.compose.foundation.gestures.calculateZoom
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.consumeAllChanges
import androidx.compose.ui.input.pointer.positionChangeConsumed
import androidx.compose.ui.input.pointer.positionChanged
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastAny
import androidx.compose.ui.util.fastForEach
import androidx.compose.ui.zIndex
import com.jvziyaoyao.scale.image.sampling.SamplingDecoder
import com.jvziyaoyao.scale.zoomable.zoomable.panTransformAndScale
import com.origeek.imageViewer.previewer.DEFAULT_CROSS_FADE_ANIMATE_SPEC
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.cancel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.absoluteValue
const val commonDeprecatedText = "com.origeek.imageViewer下的全部类和方法均已弃用! " +
"请使用新版本:com.jvziyaoyao.viewer。"
// 默认X轴偏移量
const val DEFAULT_OFFSET_X = 0F
// 默认Y轴偏移量
const val DEFAULT_OFFSET_Y = 0F
// 默认缩放率
const val DEFAULT_SCALE = 1F
// 默认旋转角度
const val DEFAULT_ROTATION = 0F
// 图片最小缩放率
const val MIN_SCALE = 0.5F
// 图片最大缩放率
const val MAX_SCALE_RATE = 3.2F
// 最小手指手势间距
const val MIN_GESTURE_FINGER_DISTANCE = 200
/**
* viewer状态对象,用于记录compose组件状态
*/
@Deprecated(
message = commonDeprecatedText,
)
class ImageViewerState(
// X轴偏移量
offsetX: Float = DEFAULT_OFFSET_X,
// Y轴偏移量
offsetY: Float = DEFAULT_OFFSET_Y,
// 缩放率
scale: Float = DEFAULT_SCALE,
// 旋转角度
rotation: Float = DEFAULT_ROTATION,
// 动画窗格
animationSpec: AnimationSpec? = null,
// 淡入淡出效果
crossfadeAnimationSpec: AnimationSpec? = null,
) : CoroutineScope by MainScope() {
// 默认动画窗格
var defaultAnimateSpec: AnimationSpec = animationSpec ?: SpringSpec()
// viewer挂载成功后显示时的动画窗格
var crossfadeAnimationSpec: AnimationSpec =
crossfadeAnimationSpec ?: DEFAULT_CROSS_FADE_ANIMATE_SPEC
// x偏移
val offsetX = Animatable(offsetX)
// y偏移
val offsetY = Animatable(offsetY)
// 放大倍率
val scale = Animatable(scale)
// 旋转
val rotation = Animatable(rotation)
// 是否允许手势输入
var allowGestureInput by mutableStateOf(true)
// 默认显示大小
var defaultSize by mutableStateOf(IntSize(0, 0))
internal set
// 容器大小
internal var containerSize by mutableStateOf(IntSize(0, 0))
// 最大缩放
internal var maxScale by mutableStateOf(1F)
// 标识是否来自saver,旋转屏幕后会变成true
internal var fromSaver = false
// 恢复的时间戳
internal var resetTimeStamp by mutableStateOf(0L)
// 挂载状态
internal val mountedFlow = MutableStateFlow(false)
/**
* 判断是否有动画正在运行
* @return Boolean
*/
internal fun isRunning(): Boolean {
return scale.isRunning
|| offsetX.isRunning
|| offsetY.isRunning
|| rotation.isRunning
}
/**
* 立即设置回初始值
*/
suspend fun resetImmediately() {
rotation.snapTo(DEFAULT_ROTATION)
offsetX.snapTo(DEFAULT_OFFSET_X)
offsetY.snapTo(DEFAULT_OFFSET_Y)
scale.snapTo(DEFAULT_SCALE)
}
/**
* 设置回初始值
*/
suspend fun reset(animationSpec: AnimationSpec = defaultAnimateSpec) {
coroutineScope {
listOf(
async {
rotation.animateTo(DEFAULT_ROTATION, animationSpec)
resetTimeStamp = System.currentTimeMillis()
},
async {
offsetX.animateTo(DEFAULT_OFFSET_X, animationSpec)
resetTimeStamp = System.currentTimeMillis()
},
async {
offsetY.animateTo(DEFAULT_OFFSET_Y, animationSpec)
resetTimeStamp = System.currentTimeMillis()
},
async {
scale.animateTo(DEFAULT_SCALE, animationSpec)
resetTimeStamp = System.currentTimeMillis()
},
).awaitAll()
}
}
/**
* 放大到最大
*/
suspend fun scaleToMax(
offset: Offset,
animationSpec: AnimationSpec? = null
) {
val currentAnimateSpec = animationSpec ?: defaultAnimateSpec
// 计算x和y偏移量和范围,并确保不会在放大过程中超出范围
var bcx = (containerSize.width / 2 - offset.x) * maxScale
val boundX = getBound(defaultSize.width.toFloat() * maxScale, containerSize.width.toFloat())
bcx = limitToBound(bcx, boundX)
var bcy = (containerSize.height / 2 - offset.y) * maxScale
val boundY =
getBound(defaultSize.height.toFloat() * maxScale, containerSize.height.toFloat())
bcy = limitToBound(bcy, boundY)
// 启动
coroutineScope {
launch {
scale.animateTo(maxScale, currentAnimateSpec)
}
launch {
offsetX.animateTo(bcx, currentAnimateSpec)
}
launch {
offsetY.animateTo(bcy, currentAnimateSpec)
}
}
}
/**
* 放大或缩小
*/
suspend fun toggleScale(
offset: Offset,
animationSpec: AnimationSpec = defaultAnimateSpec
) {
// 如果不等于1,就调回1
if (scale.value != 1F) {
reset(animationSpec)
} else {
scaleToMax(offset, animationSpec)
}
}
/**
* 修正offsetX,offsetY的位置
*/
suspend fun fixToBound() {
val boundX =
getBound(defaultSize.width.toFloat() * scale.value, containerSize.width.toFloat())
val boundY =
getBound(defaultSize.height.toFloat() * scale.value, containerSize.height.toFloat())
val limitX = limitToBound(offsetX.value, boundX)
val limitY = limitToBound(offsetY.value, boundY)
offsetX.snapTo(limitX)
offsetY.snapTo(limitY)
}
companion object {
val SAVER: Saver = listSaver(save = {
listOf(it.offsetX.value, it.offsetY.value, it.scale.value, it.rotation.value)
}, restore = {
val state = ImageViewerState(
offsetX = it[0],
offsetY = it[1],
scale = it[2],
rotation = it[3],
)
state.fromSaver = true
state
})
}
}
/**
* 记录viewer状态
* @return ImageViewerState 返回一个状态实例
*/
@Deprecated(
message = commonDeprecatedText,
)
@Composable
fun rememberViewerState(
// X轴偏移量
offsetX: Float = DEFAULT_OFFSET_X,
// Y轴偏移量
offsetY: Float = DEFAULT_OFFSET_Y,
// 缩放率
scale: Float = DEFAULT_SCALE,
// 旋转
rotation: Float = DEFAULT_ROTATION,
// 动画窗格
animationSpec: AnimationSpec? = null,
// 淡入淡出效果
crossfadeAnimationSpec: AnimationSpec? = null,
): ImageViewerState = rememberSaveable(saver = ImageViewerState.SAVER) {
ImageViewerState(offsetX, offsetY, scale, rotation, animationSpec, crossfadeAnimationSpec)
}
/**
* viewer手势对象
*/
@Deprecated(
message = commonDeprecatedText,
)
class ViewerGestureScope(
// 点击事件
var onTap: (Offset) -> Unit = {},
// 双击事件
var onDoubleTap: (Offset) -> Unit = {},
// 长按事件
var onLongPress: (Offset) -> Unit = {},
)
/**
* viewer传入的Compose数据类型参数
* @property content [@androidx.compose.runtime.Composable] [@kotlin.ExtensionFunctionType] Function1
* @constructor
*/
@Deprecated(
message = commonDeprecatedText,
)
class ComposeModel(
private val content: @Composable ComposeModel.() -> Unit = {}
) {
internal var intrinsicSize by mutableStateOf(IntSize.Zero)
fun updateIntrinsicSize(size: IntSize) {
intrinsicSize = size
}
@Composable
fun PoseContent() {
content()
}
}
/**
* model支持Painter、ImageBitmap、ImageVector、SamplingDecoder、ComposeModel
*/
@Deprecated(
message = "方法已弃用,请使用:com.jvziyaoyao.image.viewer.ImageViewer",
)
@Composable
fun ImageViewer(
// 修改参数
modifier: Modifier = Modifier,
// 图片数据
model: Any?,
// viewer状态
state: ImageViewerState = rememberViewerState(),
// 检测手势
detectGesture: ViewerGestureScope.() -> Unit = {},
// 超出容器是否显示
boundClip: Boolean = true,
// 调试模式
debugMode: Boolean = false,
) {
val viewerGestureScope = remember { ViewerGestureScope() }
detectGesture.invoke(viewerGestureScope)
val scope = rememberCoroutineScope()
// 触摸时中心位置
var centroid by remember { mutableStateOf(Offset.Zero) }
// 减速运动动画曲线
val decay = remember {
FloatExponentialDecaySpec(2f).generateDecayAnimationSpec()
}
var velocityTracker = remember { VelocityTracker() }
// 记录触摸事件中手指的个数
var eventChangeCount by remember { mutableStateOf(0) }
// 最后一次偏移运动
var lastPan by remember { mutableStateOf(Offset.Zero) }
// 手势实时的偏移范围
var boundX by remember { mutableStateOf(0F) }
var boundY by remember { mutableStateOf(0F) }
// 最大缩放率,双击的时候会放大到这个值
var maxScale by remember { mutableStateOf(1F) }
// 最大显示缩放率,缩放率超过这个值后,手势结束了就会自动恢复到这个值
val maxDisplayScale by remember { derivedStateOf { maxScale * MAX_SCALE_RATE } }
// 目标偏移量
var desX by remember { mutableStateOf(0F) }
var desY by remember { mutableStateOf(0F) }
// 目标缩放率
var desScale by remember { mutableStateOf(1F) }
// 缩放率修改前的值
var fromScale by remember { mutableStateOf(1F) }
// 计算边界使用的缩放率
var boundScale by remember { mutableStateOf(1F) }
// 目标旋转角度
var desRotation by remember { mutableStateOf(0F) }
// 要增加的旋转角度
var rotate by remember { mutableStateOf(0F) }
// 要增加的放大倍率
var zoom by remember { mutableStateOf(1F) }
// 两个手指的距离
var fingerDistanceOffset by remember { mutableStateOf(Offset.Zero) }
// 同步des的参数,在gallery的图片切换时,缩小后仍然接收手势指令,所以需要同步缩小后的参数
fun asyncDesParams() {
desX = state.offsetX.value
desY = state.offsetY.value
desScale = state.scale.value
desRotation = state.rotation.value
}
LaunchedEffect(key1 = state.resetTimeStamp) {
asyncDesParams()
}
val gesture = remember {
RawGesture(
onTap = viewerGestureScope.onTap,
onDoubleTap = viewerGestureScope.onDoubleTap,
onLongPress = viewerGestureScope.onLongPress,
gestureStart = {
if (state.allowGestureInput) {
eventChangeCount = 0
velocityTracker = VelocityTracker()
scope.launch {
state.offsetX.stop()
state.offsetY.stop()
state.offsetX.updateBounds(null, null)
state.offsetY.updateBounds(null, null)
}
asyncDesParams()
}
},
gestureEnd = { transformOnly ->
// transformOnly记录手势事件中是否有位移,如果只是点击或双击,会返回false
// 如果正在动画中,就不要执行后续动作,如:reset指令执行时
if (transformOnly && !state.isRunning() && state.allowGestureInput) {
// 处理加速度添加的点为空的情况
var velocity = try {
velocityTracker.calculateVelocity()
} catch (e: Exception) {
e.printStackTrace()
null
}
// 如果缩放比小于1,要自动回到1
// 如果缩放比大于最大显示缩放比,就设置回去,并且避免加速度
val scale = when {
state.scale.value < 1 -> 1F
state.scale.value > maxDisplayScale -> {
velocity = null
maxDisplayScale
}
else -> null
}
// 如果此时位移超出范围,就动画回范围内
// 如果没超出范围,就设置animate的范围,然后执行抛掷动画
scope.launch {
if (inBound(state.offsetX.value, boundX) && velocity != null) {
val vx = sameDirection(lastPan.x, velocity.x)
state.offsetX.updateBounds(-boundX, boundX)
state.offsetX.animateDecay(vx, decay)
} else {
val targetX = if (scale != maxDisplayScale) {
limitToBound(state.offsetX.value, boundX)
} else {
panTransformAndScale(
offset = state.offsetX.value,
center = centroid.x,
bh = state.containerSize.width.toFloat(),
uh = state.defaultSize.width.toFloat(),
fromScale = state.scale.value,
toScale = scale,
)
}
state.offsetX.animateTo(targetX)
}
}
scope.launch {
if (inBound(state.offsetY.value, boundY) && velocity != null) {
val vy = sameDirection(lastPan.y, velocity.y)
state.offsetY.updateBounds(-boundY, boundY)
state.offsetY.animateDecay(vy, decay)
} else {
val targetY = if (scale != maxDisplayScale) {
limitToBound(state.offsetY.value, boundY)
} else {
panTransformAndScale(
offset = state.offsetY.value,
center = centroid.y,
bh = state.containerSize.height.toFloat(),
uh = state.defaultSize.height.toFloat(),
fromScale = state.scale.value,
toScale = scale,
)
}
state.offsetY.animateTo(targetY)
}
}
scope.launch {
state.rotation.animateTo(0F)
}
scale?.let {
scope.launch {
state.scale.animateTo(scale)
}
}
}
},
) { center, pan, _zoom, _rotate, event ->
// 当禁止手势输入时
if (!state.allowGestureInput) return@RawGesture true
// 这里只记录最大手指数
if (event.changes.size > eventChangeCount) eventChangeCount = event.changes.size
// 如果手指数从多个变成一个,就结束本次手势操作
if (eventChangeCount > event.changes.size) return@RawGesture false
rotate = _rotate
zoom = _zoom
// 如果是双指的情况下,手指距离小于一定值时,缩放和旋转的值会很离谱,所以在这种极端情况下就不要处理缩放和旋转了
if (event.changes.size == 2) {
fingerDistanceOffset = event.changes[0].position - event.changes[1].position
if (
fingerDistanceOffset.x.absoluteValue < MIN_GESTURE_FINGER_DISTANCE
&& fingerDistanceOffset.y.absoluteValue < MIN_GESTURE_FINGER_DISTANCE
) {
rotate = 0F
zoom = 1F
}
}
// 上一次的偏移量
lastPan = pan
// 记录手势的中点
centroid = center
// 记录当前缩放比
fromScale = desScale
// 目标放大倍率
desScale *= zoom
// 检查最小放大倍率
if (desScale < MIN_SCALE) desScale = MIN_SCALE
// 计算边界,如果目标缩放值超过最大显示缩放值,边界就要用最大缩放值来计算,否则手势结束时会导致无法归位
boundScale = if (desScale > maxDisplayScale) maxDisplayScale else desScale
boundX =
getBound(boundScale * state.defaultSize.width, state.containerSize.width.toFloat())
boundY =
getBound(
boundScale * state.defaultSize.height,
state.containerSize.height.toFloat()
)
desX = panTransformAndScale(
offset = desX,
center = center.x,
bh = state.containerSize.width.toFloat(),
uh = state.defaultSize.width.toFloat(),
fromScale = fromScale,
toScale = desScale,
) + pan.x
// 如果手指数1,就是拖拽,拖拽受范围限制
// 如果手指数大于1,即有缩放事件,则支持中心点放大
if (eventChangeCount == 1) desX = limitToBound(desX, boundX)
desY = panTransformAndScale(
offset = desY,
center = center.y,
bh = state.containerSize.height.toFloat(),
uh = state.defaultSize.height.toFloat(),
fromScale = fromScale,
toScale = desScale,
) + pan.y
if (eventChangeCount == 1) desY = limitToBound(desY, boundY)
if (desScale < 1) desRotation += rotate
velocityTracker.addPosition(
event.changes[0].uptimeMillis,
Offset(desX, desY),
)
if (!state.isRunning()) scope.launch {
state.scale.snapTo(desScale)
state.offsetX.snapTo(desX)
state.offsetY.snapTo(desY)
state.rotation.snapTo(desRotation)
}
// 这里判断是否已运动到边界,如果到了边界,就不消费事件,让上层界面获取到事件
val onLeft = desX >= boundX
val onRight = desX <= -boundX
val reachSide = !(onLeft && pan.x > 0)
&& !(onRight && pan.x < 0)
&& !(onLeft && onRight)
if (reachSide || state.scale.value < 1) {
event.changes.fastForEach {
if (it.positionChanged()) {
it.consumeAllChanges()
}
}
}
// 返回true,继续下一次手势
return@RawGesture true
}
}
val sizeChange: suspend (SizeChangeContent) -> Unit = { content ->
maxScale = content.maxScale
state.defaultSize = content.defaultSize
state.containerSize = content.containerSize
state.maxScale = content.maxScale
if (state.fromSaver) {
state.fromSaver = false
state.fixToBound()
}
}
Box(modifier = modifier) {
/**
* 将挂载信息通知到state
*/
val onMounted: () -> Unit = {
scope.launch {
state.mountedFlow.emit(true)
}
}
/**
* 根据不同类型的model进行不同的渲染
*/
when (model) {
is Painter,
is ImageVector,
is ImageBitmap,
is ComposeModel,
-> {
ImageComposeOrigin(
model = model,
scale = state.scale.value,
offsetX = state.offsetX.value,
offsetY = state.offsetY.value,
rotation = state.rotation.value,
gesture = gesture,
onSizeChange = sizeChange,
onMounted = onMounted,
boundClip = boundClip,
crossfadeAnimationSpec = state.crossfadeAnimationSpec,
)
}
is SamplingDecoder -> {
ImageComposeCanvas(
samplingDecoder = model,
scale = state.scale.value,
offsetX = state.offsetX.value,
offsetY = state.offsetY.value,
rotation = state.rotation.value,
gesture = gesture,
onSizeChange = sizeChange,
onMounted = onMounted,
boundClip = boundClip,
crossfadeAnimationSpec = state.crossfadeAnimationSpec,
)
}
}
/**
* 调试模式
*/
if (debugMode) {
Box(
modifier = Modifier
.fillMaxSize()
.zIndex(10F)
) {
if (model != null) {
Text(text = "Model -> ON", Modifier.background(Color.White))
}
Box(
modifier = Modifier
.graphicsLayer {
translationX = centroid.x - 6.dp.toPx()
translationY = centroid.y - 6.dp.toPx()
}
.clip(CircleShape)
.background(Color.Red.copy(0.4f))
.size(12.dp)
)
}
}
}
}
/**
* 重写事件监听方法
*/
suspend fun PointerInputScope.detectTransformGestures(
panZoomLock: Boolean = false,
gestureStart: () -> Unit = {},
gestureEnd: (Boolean) -> Unit = {},
onTap: (Offset) -> Unit = {},
onDoubleTap: (Offset) -> Unit = {},
onGesture: (centroid: Offset, pan: Offset, zoom: Float, rotation: Float, event: PointerEvent) -> Boolean,
) {
var lastReleaseTime = 0L
var scope: CoroutineScope? = null
forEachGesture {
awaitPointerEventScope {
var rotation = 0f
var zoom = 1f
var pan = Offset.Zero
var pastTouchSlop = false
val touchSlop = viewConfiguration.touchSlop
var lockedToPanZoom = false
awaitFirstDown(requireUnconsumed = false)
val t0 = System.currentTimeMillis()
var releasedEvent: PointerEvent? = null
var moveCount = 0
// 这里开始事件
gestureStart()
do {
val event = awaitPointerEvent()
if (event.type == PointerEventType.Release) releasedEvent = event
if (event.type == PointerEventType.Move) moveCount++
val canceled = event.changes.fastAny { it.positionChangeConsumed() }
if (!canceled) {
val zoomChange = event.calculateZoom()
val rotationChange = event.calculateRotation()
val panChange = event.calculatePan()
if (!pastTouchSlop) {
zoom *= zoomChange
rotation += rotationChange
pan += panChange
val centroidSize = event.calculateCentroidSize(useCurrent = false)
val zoomMotion = abs(1 - zoom) * centroidSize
val rotationMotion = abs(rotation * PI.toFloat() * centroidSize / 180f)
val panMotion = pan.getDistance()
if (zoomMotion > touchSlop ||
rotationMotion > touchSlop ||
panMotion > touchSlop
) {
pastTouchSlop = true
lockedToPanZoom = panZoomLock && rotationMotion < touchSlop
}
}
if (pastTouchSlop) {
val centroid = event.calculateCentroid(useCurrent = false)
val effectiveRotation = if (lockedToPanZoom) 0f else rotationChange
if (effectiveRotation != 0f ||
zoomChange != 1f ||
panChange != Offset.Zero
) {
if (!onGesture(
centroid,
panChange,
zoomChange,
effectiveRotation,
event
)
) break
}
}
}
} while (!canceled && event.changes.fastAny { it.pressed })
var t1 = System.currentTimeMillis()
val dt = t1 - t0
val dlt = t1 - lastReleaseTime
if (moveCount == 0) releasedEvent?.let { e ->
if (e.changes.isEmpty()) return@let
val offset = e.changes.first().position
if (dlt < 272) {
t1 = 0L
scope?.cancel()
onDoubleTap(offset)
} else if (dt < 200) {
scope = MainScope()
scope?.launch(Dispatchers.Main) {
delay(272)
onTap(offset)
}
}
lastReleaseTime = t1
}
// 这里是事件结束
gestureEnd(moveCount != 0)
}
}
}
/**
* 让后一个数与前一个数的符号保持一致
* @param a Float
* @param b Float
* @return Float
*/
fun sameDirection(a: Float, b: Float): Float {
return if (a > 0) {
if (b < 0) {
b.absoluteValue
} else {
b
}
} else {
if (b > 0) {
-b
} else {
b
}
}
}
/**
* 获取移动边界
*/
fun getBound(rw: Float, bw: Float): Float {
return if (rw > bw) {
var xb = (rw - bw).div(2)
if (xb < 0) xb = 0F
xb
} else {
0F
}
}
/**
* 判断位移是否在边界内
*/
fun inBound(offset: Float, bound: Float): Boolean {
return if (offset > 0) {
offset < bound
} else if (offset < 0) {
offset > -bound
} else {
true
}
}
/**
* 把位移限制在边界内
*/
fun limitToBound(offset: Float, bound: Float): Float {
return when {
offset > bound -> {
bound
}
offset < -bound -> {
-bound
}
else -> {
offset
}
}
}
================================================
FILE: scale-image-viewer-classic/src/test/java/com/jvziyaoyao/scale/image/classic/ExampleUnitTest.kt
================================================
package com.jvziyaoyao.scale.image.classic
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
================================================
FILE: scale-sampling-decoder/.gitignore
================================================
/build
================================================
FILE: scale-sampling-decoder/build.gradle.kts
================================================
import scale.applyScaleHierarchyTemplate
import scale.compileSdk
import scale.minSdk
plugins {
id("com.android.kotlin.multiplatform.library")
id("org.jetbrains.kotlin.plugin.compose")
id("org.jetbrains.kotlin.multiplatform")
id("com.vanniktech.maven.publish")
id("org.jetbrains.compose")
id("org.jetbrains.dokka")
}
kotlin {
applyScaleHierarchyTemplate()
androidLibrary {
namespace = "com.jvziyaoyao.scale.image.sampling"
compileSdk = project.compileSdk
minSdk = project.minSdk
}
jvm()
val xcfName = "samplingDecoderKit"
iosX64 {
binaries.framework {
baseName = xcfName
}
}
iosArm64 {
binaries.framework {
baseName = xcfName
}
}
iosSimulatorArm64 {
binaries.framework {
baseName = xcfName
}
}
sourceSets {
commonMain {
dependencies {
implementation(project(":scale-image-viewer"))
implementation(project(":scale-zoomable-view"))
implementation(libs.bignum)
implementation(libs.kotlin.stdlib)
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.ui)
implementation(compose.components.resources)
implementation(compose.components.uiToolingPreview)
implementation(libs.org.jetbrains.kotlinx.datetime)
}
}
commonTest {
dependencies {
implementation(libs.kotlin.test)
}
}
androidMain {
dependencies {
implementation(libs.androidx.exif)
}
}
named("nonAndroidMain") {
dependencies {
implementation(libs.skiko)
}
}
iosMain {
dependencies {}
}
}
}
================================================
FILE: scale-sampling-decoder/gradle.properties
================================================
POM_ARTIFACT_ID=sampling-decoder
POM_NAME=sampling-decoder
POM_PACKAGING=aar
================================================
FILE: scale-sampling-decoder/src/androidMain/AndroidManifest.xml
================================================
================================================
FILE: scale-sampling-decoder/src/androidMain/kotlin/com/jvziyaoyao/scale/image/sampling/RegionDecoder.android.kt
================================================
package com.jvziyaoyao.scale.image.sampling
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.BitmapRegionDecoder
import android.graphics.Matrix
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asAndroidBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.exifinterface.media.ExifInterface
actual fun getReginDecoder(bytes: ByteArray?): RegionDecoder? {
if (bytes == null) return null
val bitmapRegionDecoder = BitmapRegionDecoder.newInstance(bytes, 0, bytes.size, false)
return AndroidRegionDecoder(bitmapRegionDecoder)
}
/**
* 通过Exif接口获取SamplingDecoder的旋转方向
*
* @return
*/
fun ExifInterface.getDecoderRotation(): SamplingDecoder.Rotation {
val orientation = getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL
)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> SamplingDecoder.Rotation.ROTATION_90
ExifInterface.ORIENTATION_ROTATE_180 -> SamplingDecoder.Rotation.ROTATION_180
ExifInterface.ORIENTATION_ROTATE_270 -> SamplingDecoder.Rotation.ROTATION_270
else -> SamplingDecoder.Rotation.ROTATION_0
}
}
fun Rect.toAndroidRect(): android.graphics.Rect {
return android.graphics.Rect(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
}
class AndroidRegionDecoder(
private val decoder: BitmapRegionDecoder,
) : RegionDecoder {
override fun width(): Int {
return decoder.width
}
override fun height(): Int {
return decoder.height
}
override fun recycle() {
decoder.recycle()
}
override fun isRecycled(): Boolean {
return decoder.isRecycled
}
override fun rotate(
imageBitmap: ImageBitmap,
degree: Float
): ImageBitmap {
val matrix = Matrix()
matrix.postRotate(degree)
val bitmap = imageBitmap.asAndroidBitmap()
val result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, false)
return result.asImageBitmap()
}
override suspend fun decodeRegion(
inSampleSize: Int,
rect: Rect
): ImageBitmap? {
val bitmap = try {
if (decoder.isRecycled) return null
val ops = BitmapFactory.Options()
ops.inSampleSize = inSampleSize
decoder.decodeRegion(rect.toAndroidRect(), ops)
} catch (e: Exception) {
e.printStackTrace()
null
}
return bitmap?.asImageBitmap()
}
}
================================================
FILE: scale-sampling-decoder/src/commonMain/kotlin/com/jvziyaoyao/scale/image/sampling/BlockingDeque.kt
================================================
package com.jvziyaoyao.scale.image.sampling
import com.jvziyaoyao.scale.zoomable.util.getMilliseconds
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class BlockingDeque {
private val deque = ArrayDeque()
private val mutex = Mutex()
private val flow = MutableSharedFlow()
suspend fun putFirst(element: T) = mutex.withLock {
deque.addFirst(element)
flow.emit(getMilliseconds())
}
suspend fun removeFirst(): T = mutex.withLock {
return@withLock deque.removeFirst()
}
suspend fun take(): T {
if (deque.isEmpty()) {
flow.first()
}
return removeFirst()
}
suspend fun clear() = mutex.withLock { deque.clear() }
suspend fun size(): Int = mutex.withLock { deque.size }
suspend fun isEmpty(): Boolean = mutex.withLock { deque.isEmpty() }
suspend fun peekFirst(): T? = mutex.withLock { deque.firstOrNull() }
suspend fun peekLast(): T? = mutex.withLock { deque.lastOrNull() }
fun contains(element: T): Boolean = deque.contains(element)
suspend fun remove(element: T) = mutex.withLock { deque.remove(element) }
}
================================================
FILE: scale-sampling-decoder/src/commonMain/kotlin/com/jvziyaoyao/scale/image/sampling/RegionDecoder.kt
================================================
package com.jvziyaoyao.scale.image.sampling
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.ImageBitmap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.launch
interface RegionDecoder {
fun width(): Int
fun height(): Int
fun recycle()
fun isRecycled(): Boolean
fun rotate(imageBitmap: ImageBitmap, degree: Float): ImageBitmap
suspend fun decodeRegion(
inSampleSize: Int,
rect: Rect,
): ImageBitmap?
}
class IllegalDecoderModelException : RuntimeException("illegal region decoder model type!")
expect fun getReginDecoder(bytes: ByteArray?): RegionDecoder?
@Composable
fun rememberSamplingDecoder(
bytes: ByteArray?,
rotation: SamplingDecoder.Rotation = SamplingDecoder.Rotation.ROTATION_0,
): Pair {
val scope = rememberCoroutineScope()
val samplingDecoder = remember { mutableStateOf(null) }
val expectation = remember { mutableStateOf(null) }
DisposableEffect(bytes, rotation) {
var currentSamplingDecoder: SamplingDecoder? = null
scope.launch(Dispatchers.IO) {
if (bytes != null) {
try {
val reginDecoder = getReginDecoder(bytes = bytes)
if (reginDecoder != null) {
currentSamplingDecoder = SamplingDecoder(
decoder = reginDecoder,
rotation = rotation,
).apply {
thumbnail = createTempBitmap()
}
samplingDecoder.value = currentSamplingDecoder
}
} catch (e: Exception) {
expectation.value = e
}
}
}
onDispose {
scope.launch {
currentSamplingDecoder?.release()
}
}
}
return Pair(samplingDecoder.value, expectation.value)
}
================================================
FILE: scale-sampling-decoder/src/commonMain/kotlin/com/jvziyaoyao/scale/image/sampling/SamplingCanvas.kt
================================================
package com.jvziyaoyao.scale.image.sampling
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import com.ionspin.kotlin.bignum.decimal.BigDecimal
import com.ionspin.kotlin.bignum.decimal.DecimalMode
import com.ionspin.kotlin.bignum.decimal.RoundingMode
import com.jvziyaoyao.scale.zoomable.util.getMilliseconds
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableViewState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.math.max
import kotlin.math.min
/**
* @program: SamplingCanvas
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-12-01 22:02
**/
/**
* 渲染的视口对象
*
* @property scale 图片相对显示倍率,相对于1倍屏幕显示倍率
* @property visualRect 在视口内的归一化坐标
*/
data class SamplingCanvasViewPort(
val scale: Float,
val visualRect: Rect,
)
/**
* 从ZoomableView状态直接获取当前视口对象
*
* @return
*/
fun ZoomableViewState.getViewPort(): SamplingCanvasViewPort {
val realWidth = realSize.width
val realHeight = realSize.height
val containerCenterX = containerWidth.div(2)
val containerCenterY = containerHeight.div(2)
val displayLeft = containerCenterX - realWidth.div(2)
val displayTop = containerCenterY - realHeight.div(2)
val left = displayLeft + offsetX.value
val top = displayTop + offsetY.value
val right = left + realWidth
val bottom = top + realHeight
val realRect = Rect(left, top, right, bottom)
val containerRect = Rect(0F, 0F, containerWidth, containerHeight)
val intersectRect = intersectRect(realRect, containerRect)
val rectInViewPort = Rect(
left = (intersectRect.left - realRect.left).div(realWidth),
top = (intersectRect.top - realRect.top).div(realHeight),
right = (intersectRect.right - realRect.left).div(realWidth),
bottom = (intersectRect.bottom - realRect.top).div(realHeight),
)
return SamplingCanvasViewPort(
scale = scale.value,
visualRect = rectInViewPort,
)
}
internal fun intersectRect(rect1: Rect, rect2: Rect): Rect {
val left = max(rect1.left, rect2.left)
val top = max(rect1.top, rect2.top)
val right = min(rect1.right, rect2.right)
val bottom = min(rect1.bottom, rect2.bottom)
return if (left < right && top < bottom) {
Rect(left, top, right, bottom)
} else {
Rect(0F, 0F, 0F, 0F)
}
}
fun calculateInSampleSize(
srcWidth: Int,
reqWidth: Int,
): Int {
var inSampleSize = 1
while (true) {
val iss = inSampleSize * 2
if (srcWidth.toFloat().div(iss) < reqWidth) break
inSampleSize = iss
}
return inSampleSize
}
fun checkRectInBound(
stX1: Float, stY1: Float, edX1: Float, edY1: Float,
stX2: Float, stY2: Float, edX2: Float, edY2: Float,
): Boolean {
if (edY1 < stY2) return false
if (stY1 > edY2) return false
if (edX1 < stX2) return false
if (stX1 > edX2) return false
return true
}
internal infix fun Rect.same(other: Rect): Boolean {
return this.left == other.left
&& this.right == other.right
&& this.top == other.top
&& this.bottom == other.bottom
}
/**
* 用于ImageViewer/ZoomableView进行分块显示大型图片的配套组件
*
* @param samplingDecoder 图片加载器
* @param viewPort 视口
*/
@Composable
fun SamplingCanvas(
samplingDecoder: SamplingDecoder,
viewPort: SamplingCanvasViewPort,
) {
val scope = rememberCoroutineScope()
val density = LocalDensity.current
BoxWithConstraints(
modifier = Modifier
.fillMaxSize()
) {
val maxWidthPx = density.run { this@BoxWithConstraints.maxWidth.toPx() }
val maxHeightPx = density.run { this@BoxWithConstraints.maxHeight.toPx() }
val realWidth = maxWidthPx.times(viewPort.scale)
val realHeight = maxHeightPx.times(viewPort.scale)
// 判断是否需要高画质渲染
val needRenderHeightTexture by remember(maxWidthPx, maxHeightPx) {
derivedStateOf {
// 目前策略:原图的面积大于容器面积,就要渲染高画质
BigDecimal.fromInt(samplingDecoder.decoderWidth)
.multiply(BigDecimal.fromInt(samplingDecoder.decoderHeight)) > BigDecimal.fromDouble(
maxHeightPx.toDouble()
)
.multiply(BigDecimal.fromDouble(maxWidthPx.toDouble()))
}
}
// 标识当前是否开启高画质渲染,如果需要高画质渲染,并且缩放大于1
val renderHeightTexture by remember(key1 = viewPort.scale) { derivedStateOf { needRenderHeightTexture && viewPort.scale > 1 } }
// 当前采样率
val inSampleSize by remember(realWidth) {
derivedStateOf {
calculateInSampleSize(
srcWidth = samplingDecoder.decoderWidth,
reqWidth = realWidth.toInt()
)
}
}
// 最小图的采样率
val zeroInSampleSize by remember {
derivedStateOf {
calculateInSampleSize(
srcWidth = samplingDecoder.decoderWidth,
reqWidth = maxWidthPx.toInt(),
)
}
}
val backgroundInputSample by remember(
zeroInSampleSize,
inSampleSize,
needRenderHeightTexture
) {
derivedStateOf {
if (needRenderHeightTexture) zeroInSampleSize else inSampleSize
}
}
var bitmap by remember { mutableStateOf(samplingDecoder.thumbnail) }
LaunchedEffect(backgroundInputSample) {
scope.launch(Dispatchers.IO) {
bitmap = samplingDecoder.decodeRegion(
backgroundInputSample, Rect(
Offset.Zero,
Size(
samplingDecoder.decoderWidth.toFloat(),
samplingDecoder.decoderHeight.toFloat(),
)
)
)
}
}
// DisposableEffect(Unit) {
// onDispose {
// bitmap?.recycle()
// bitmap = null
// }
// }
// 更新时间戳,用于通知canvas更新方块
var renderUpdateTimeStamp by remember { mutableStateOf(0L) }
// 开启解码队列的循环
LaunchedEffect(key1 = Unit) {
samplingDecoder.startRenderQueue {
// 解码器解码一个,就更新一次时间戳
renderUpdateTimeStamp = getMilliseconds()
}
}
// 切换到不需要高画质渲染时,需要清除解码队列,清除全部的bitmap
LaunchedEffect(key1 = renderHeightTexture) {
if (!renderHeightTexture) {
samplingDecoder.renderQueue.clear()
samplingDecoder.clearAllBitmap()
}
}
/**
* 更新渲染队列
*/
var calcMaxCountPending by remember { mutableStateOf(false) }
// 先前的缩放比
var previousScale by remember { mutableStateOf(null) }
// 先前的偏移量
var previousVisualRect by remember { mutableStateOf(null) }
// 记录最长边的最大方块数
var blockDividerCount by remember { mutableStateOf(1) }
// 用来标识这个参数是否有改变
var preBlockDividerCount by remember { mutableStateOf(blockDividerCount) }
val stX = realWidth.times(viewPort.visualRect.left)
val stY = realHeight.times(viewPort.visualRect.top)
val edX = realWidth.times(viewPort.visualRect.right)
val edY = realHeight.times(viewPort.visualRect.bottom)
val visualRectWidth = maxWidth.times(viewPort.visualRect.width)
val visualRectHeight = maxHeight.times(viewPort.visualRect.height)
val mutex = remember { Mutex() }
// 更新渲染方块的信息
fun updateRenderList() {
// 如果此时正在重新计算渲染方块的数目,就退出
if (calcMaxCountPending) return
// 更新的时候如果缩放和偏移量没有变化,方块数量也没变,就没有必要计算了
if (
previousVisualRect?.same(viewPort.visualRect) == true
&& previousScale == viewPort.scale
&& preBlockDividerCount == blockDividerCount
) return
previousVisualRect = viewPort.visualRect
previousScale = viewPort.scale
// 计算当前渲染方块大小
val renderBlockSize =
samplingDecoder.blockSize * (realWidth.div(samplingDecoder.decoderWidth))
var tlx: Int
var tly: Int
var startX: Float
var startY: Float
var endX: Float
var endY: Float
var eh: Int
var ew: Int
var needUpdate: Boolean
var previousInBound: Boolean
var previousInSampleSize: Int
var lastX: Int?
var lastY: Int? = null
var lastXDelta: Int
var lastYDelta: Int
val insertList = ArrayList()
val removeList = ArrayList()
for ((column, list) in samplingDecoder.renderList.withIndex()) {
startY = column * renderBlockSize
endY = (column + 1) * renderBlockSize
tly = startY.toInt()
eh = (if (endY > realHeight) realHeight - startY else renderBlockSize).toInt()
// 由于计算的精度问题,需要确保每一个区块都要严丝合缝
lastY?.let {
if (it < tly) {
lastYDelta = tly - it
tly = it
eh += lastYDelta
}
}
lastY = tly + eh
lastX = null
for ((row, block) in list.withIndex()) {
startX = row * renderBlockSize
tlx = startX.toInt()
endX = (row + 1) * renderBlockSize
ew = (if (endX > realWidth) realWidth - startX else renderBlockSize).toInt()
previousInSampleSize = block.inSampleSize
previousInBound = block.inBound
// 记录当前区块的采用率
block.inSampleSize = inSampleSize
// 判断区块是否在可视范围内
block.inBound = checkRectInBound(
startX, startY, endX, endY,
stX, stY, edX, edY
)
// 由于计算的精度问题,需要确保每一个区块都要严丝合缝
lastX?.let {
if (it < tlx) {
lastXDelta = tlx - it
tlx = it
ew += lastXDelta
}
}
lastX = tlx + ew
// 记录区块的实际偏移量
block.renderOffset = IntOffset(tlx, tly)
// 记录区块的实际大小
block.renderSize = IntSize(
width = ew,
height = eh,
)
// 如果参数跟之前的一样,就没有必要更新bitmap
needUpdate = previousInBound != block.inBound
|| previousInSampleSize != block.inSampleSize
if (!needUpdate) continue
if (!renderHeightTexture) continue
// 解码队列操作时是有锁的,会对性能造成影响
if (block.inBound) {
if (!samplingDecoder.renderQueue.contains(block)) {
insertList.add(block)
}
} else {
removeList.add(block)
block.release()
}
}
}
scope.launch(Dispatchers.IO) {
mutex.withLock {
insertList.forEach {
samplingDecoder.renderQueue.putFirst(it)
}
removeList.forEach {
samplingDecoder.renderQueue.remove(it)
}
}
}
}
LaunchedEffect(realWidth, realHeight, viewPort.visualRect) {
// 可视区域面积
val rectArea = BigDecimal.fromDouble(visualRectWidth.value.toDouble())
.multiply(BigDecimal.fromDouble(visualRectHeight.value.toDouble()))
// 实际大小面积
val realArea =
BigDecimal.fromDouble(realWidth.toDouble())
.multiply(BigDecimal.fromDouble(realHeight.toDouble()))
// 被除数不能为0
if (realArea.toPlainString().toFloat() == 0F) return@LaunchedEffect
// 计算实际面积的可视率
val renderAreaPercentage =
rectArea.divide(realArea, DecimalMode(2, RoundingMode.ROUND_HALF_TO_EVEN))
// 根据不同可视率,匹配合适的方块数,最大只能到8
val goBlockDividerCount = when {
renderAreaPercentage > 0.6F -> 1
renderAreaPercentage > 0.025F -> 4
else -> 8
}
// 如果没变,就不要修改
if (goBlockDividerCount == blockDividerCount) return@LaunchedEffect
preBlockDividerCount = blockDividerCount
blockDividerCount = goBlockDividerCount
scope.launch(Dispatchers.IO) {
// 清空解码队列
samplingDecoder.renderQueue.clear()
// 进入修改区间
calcMaxCountPending = true
samplingDecoder.setMaxBlockCount(blockDividerCount)
calcMaxCountPending = false
// 离开修改区间
// 更新一下界面
updateRenderList()
}
}
Canvas(
modifier = Modifier
.fillMaxSize(),
) {
val backScale = 1F.div(viewPort.scale)
withTransform({
scale(backScale, backScale, pivot = Offset(0.5F, 0.5F))
}) {
if (bitmap != null) {
drawImage(
image = bitmap!!,
dstSize = IntSize(realWidth.toInt(), realHeight.toInt()),
)
}
// 更新渲染队列
if (renderUpdateTimeStamp >= 0) updateRenderList()
if (renderHeightTexture && !calcMaxCountPending) {
samplingDecoder.forEachBlock { block, _, _ ->
block.getBitmap()?.let {
drawImage(
image = it,
dstSize = block.renderSize,
dstOffset = block.renderOffset
)
}
}
}
}
}
}
}
================================================
FILE: scale-sampling-decoder/src/commonMain/kotlin/com/jvziyaoyao/scale/image/sampling/SamplingDecoder.kt
================================================
package com.jvziyaoyao.scale.image.sampling
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.math.ceil
class RotationIllegalException(msg: String = "Illegal rotation angle.") : RuntimeException(msg)
data class RenderBlock(
var inBound: Boolean = false,
var inSampleSize: Int = 1,
var renderOffset: IntOffset = IntOffset.Zero,
var renderSize: IntSize = IntSize.Zero,
var sliceRect: Rect = Rect(Offset.Zero, Size.Zero),
private var bitmap: ImageBitmap? = null,
) {
fun release() {
// bitmap?.recycle()
bitmap = null
}
fun getBitmap(): ImageBitmap? {
return bitmap
}
fun setBitmap(bitmap: ImageBitmap) {
this.bitmap = bitmap
}
}
fun Channel.clear() {
while (true) {
val result = this.tryReceive()
if (result.isFailure) break
}
}
/**
* 用以提供SamplingCanvas显示大型图片,rememberSamplingDecoder,createSamplingDecoder
*
* @property decoder 图源BitmapRegionDecoder
* @property rotation 图片的旋转角度,通过Exif接口获取文件的旋转角度后可以设置rotation确保图像的正确显示
* @property onRelease 资源缩放事件
* @constructor
*
* @param thumbnails 默认显示的缓存图片,图片未完成加载时可用于显示占位
*/
class SamplingDecoder(
private val decoder: RegionDecoder,
private val rotation: Rotation = Rotation.ROTATION_0,
private val onRelease: () -> Unit = {},
thumbnails: ImageBitmap? = null,
) : CoroutineScope by MainScope() {
private val mutex = Mutex()
enum class Rotation(val radius: Int) {
ROTATION_0(0),
ROTATION_90(90),
ROTATION_180(180),
ROTATION_270(270),
;
}
var thumbnail by mutableStateOf(thumbnails)
// 解码的宽度
var decoderWidth by mutableStateOf(0)
private set
// 解码的高度
var decoderHeight by mutableStateOf(0)
private set
// 解码大小
val intrinsicSize: Size
get() {
return Size(
width = decoderWidth.toFloat(),
height = decoderHeight.toFloat(),
)
}
// 解码区块大小
var blockSize by mutableStateOf(0)
private set
// 渲染列表
var renderList: Array> = emptyArray()
private set
// 解码渲染队列
// val renderQueue = LinkedBlockingDeque()
val renderQueue = BlockingDeque()
// 横向方块数
private var countW = 0
// 纵向方块数
private var countH = 0
// 最长边的最大方块数
private var maxBlockCount = 0
init {
// 初始化最大方块数
setMaxBlockCount(1)
}
// 构造一个渲染方块队列
private fun getRenderBlockList(): Array> {
var endX: Int
var endY: Int
var sliceStartX: Int
var sliceStartY: Int
var sliceEndX: Int
var sliceEndY: Int
return Array(countH) { column ->
sliceStartY = (column * blockSize)
endY = (column + 1) * blockSize
sliceEndY = if (endY > decoderHeight) decoderHeight else endY
Array(countW) { row ->
sliceStartX = (row * blockSize)
endX = (row + 1) * blockSize
sliceEndX = if (endX > decoderWidth) decoderWidth else endX
RenderBlock(
sliceRect = Rect(
sliceStartX.toFloat(),
sliceStartY.toFloat(),
sliceEndX.toFloat(),
sliceEndY.toFloat(),
)
)
}
}
}
// 设置最长边最大方块数
fun setMaxBlockCount(count: Int): Boolean {
if (maxBlockCount == count) return false
if (decoder.isRecycled()) return false
when (rotation) {
Rotation.ROTATION_0, Rotation.ROTATION_180 -> {
decoderWidth = decoder.width()
decoderHeight = decoder.height()
}
Rotation.ROTATION_90, Rotation.ROTATION_270 -> {
decoderWidth = decoder.height()
decoderHeight = decoder.width()
}
}
maxBlockCount = count
blockSize =
(decoderWidth.coerceAtLeast(decoderHeight)).toFloat().div(count).toInt()
countW = ceil(decoderWidth.toFloat().div(blockSize)).toInt()
countH = ceil(decoderHeight.toFloat().div(blockSize)).toInt()
renderList = getRenderBlockList()
return true
}
// 遍历每一个渲染方块
fun forEachBlock(action: (block: RenderBlock, column: Int, row: Int) -> Unit) {
for ((column, rows) in renderList.withIndex()) {
for ((row, block) in rows.withIndex()) {
action(block, column, row)
}
}
}
// 清除全部bitmap的引用
fun clearAllBitmap() {
forEachBlock { block, _, _ ->
block.release()
}
}
// 释放资源
@OptIn(InternalCoroutinesApi::class)
suspend fun release() {
// thumbnail?.recycle()
thumbnail = null
mutex.withLock {
if (!decoder.isRecycled()) {
// 清除渲染队列
renderQueue.clear()
// 回收资源
decoder.recycle()
// 发送一个信号停止堵塞的循环
renderQueue.putFirst(RenderBlock())
}
onRelease()
}
}
fun getRotationSize(rotation: Rotation): IntSize {
return when (rotation) {
Rotation.ROTATION_0, Rotation.ROTATION_180 -> {
IntSize(decoder.width(), decoder.height())
}
Rotation.ROTATION_90, Rotation.ROTATION_270 -> {
IntSize(decoder.height(), decoder.width())
}
}
}
/**
* 解码渲染区域
*/
suspend fun decodeRegion(inSampleSize: Int, rect: Rect): ImageBitmap? {
return mutex.withLock {
if (rotation == Rotation.ROTATION_0) {
decoder.decodeRegion(inSampleSize, rect)
} else {
val size = getRotationSize(rotation)
val decoderWidth = size.width
val decoderHeight = size.height
val newRect = when (rotation) {
Rotation.ROTATION_90 -> {
val nextX1 = rect.top
val nextX2 = rect.bottom
val nextY1 = decoderWidth - rect.right
val nextY2 = decoderWidth - rect.left
Rect(nextX1, nextY1, nextX2, nextY2)
}
Rotation.ROTATION_180 -> {
val nextX1 = decoderWidth - rect.right
val nextX2 = decoderWidth - rect.left
val nextY1 = decoderHeight - rect.bottom
val nextY2 = decoderHeight - rect.top
Rect(nextX1, nextY1, nextX2, nextY2)
}
Rotation.ROTATION_270 -> {
val nextX1 = decoderHeight - rect.bottom
val nextX2 = decoderHeight - rect.top
val nextY1 = rect.left
val nextY2 = rect.right
Rect(nextX1, nextY1, nextX2, nextY2)
}
else -> throw RotationIllegalException()
}
val bitmap = decoder.decodeRegion(inSampleSize, newRect)
if (bitmap == null) bitmap else {
decoder.rotate(bitmap, rotation.radius.toFloat())
}
}
}
}
// 开启堵塞队列的循环
fun startRenderQueue(onUpdate: () -> Unit) {
launch(Dispatchers.IO) {
try {
while (!decoder.isRecycled()) {
val block = renderQueue.take()
if (decoder.isRecycled()) break
val bitmap = decodeRegion(block.inSampleSize, block.sliceRect)
if (bitmap != null) block.setBitmap(bitmap)
onUpdate()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
suspend fun createTempBitmap(targetWidth: Int = 720): ImageBitmap? {
val inputSample = calculateInSampleSize(
srcWidth = decoderWidth,
reqWidth = targetWidth,
)
return decodeRegion(
inputSample,
Rect(
offset = Offset.Zero,
size = Size(
width = decoderWidth.toFloat(),
height = decoderHeight.toFloat(),
),
)
)
}
}
================================================
FILE: scale-sampling-decoder/src/commonMain/kotlin/com/jvziyaoyao/scale/image/sampling/SamplingProcessor.kt
================================================
package com.jvziyaoyao.scale.image.sampling
import com.jvziyaoyao.scale.image.viewer.ModelProcessorPair
val samplingProcessorPair: ModelProcessorPair = SamplingDecoder::class to { model, state ->
SamplingCanvas(
samplingDecoder = model as SamplingDecoder,
viewPort = state.getViewPort(),
)
}
================================================
FILE: scale-sampling-decoder/src/nonAndroidMain/kotlin/com/jvziyaoyao/scale/image/sampling/RegionDecoder.nonAndroid.kt
================================================
package com.jvziyaoyao.scale.image.sampling
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asComposeImageBitmap
import androidx.compose.ui.graphics.asSkiaBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import androidx.compose.ui.graphics.toSkiaRect
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.Canvas
import org.jetbrains.skia.Image
import org.jetbrains.skia.Surface
import kotlin.math.ceil
import kotlin.math.roundToInt
actual fun getReginDecoder(bytes: ByteArray?): RegionDecoder? {
if (bytes == null) return null
return SkiaRegionDecoder(bytes = bytes)
}
class SkiaRegionDecoder(
private val bytes: ByteArray,
) : RegionDecoder {
private val image: Image by lazy { Image.makeFromEncoded(bytes) }
override fun width(): Int {
return image.width
}
override fun height(): Int {
return image.height
}
override fun recycle() {
image.close()
}
override fun isRecycled(): Boolean {
return image.isClosed
}
override fun rotate(imageBitmap: ImageBitmap, degree: Float): ImageBitmap {
val skiaBitmap = imageBitmap.asSkiaBitmap()
val skiaImage = Image.makeFromBitmap(skiaBitmap)
val width = skiaImage.width
val height = skiaImage.height
val normalizedDegree = (((degree % 360) + 360) % 360).roundToInt()
val rotation = when (normalizedDegree) {
in 45..134 -> 90
in 135..224 -> 180
in 225..314 -> 270
else -> 0
}
val (outWidth, outHeight) = if (rotation == 90 || rotation == 270) {
height to width
} else {
width to height
}
val surface = Surface.makeRasterN32Premul(outWidth, outHeight)
val canvas = surface.canvas
// 关键:调整坐标原点后再旋转
when (rotation) {
90 -> {
canvas.translate(outWidth.toFloat(), 0f)
canvas.rotate(90f)
}
180 -> {
canvas.translate(outWidth.toFloat(), outHeight.toFloat())
canvas.rotate(180f)
}
270 -> {
canvas.translate(0f, outHeight.toFloat())
canvas.rotate(270f)
}
// 0 -> 不需要变换
}
canvas.drawImage(skiaImage, 0f, 0f)
return surface.makeImageSnapshot().toComposeImageBitmap()
}
override suspend fun decodeRegion(
inSampleSize: Int,
rect: Rect
): ImageBitmap? {
val widthValue = rect.width / inSampleSize.toDouble()
val heightValue = rect.height / inSampleSize.toDouble()
val bitmapWidth: Int = ceil(widthValue).toInt()
val bitmapHeight: Int = ceil(heightValue).toInt()
val bitmap = Bitmap().apply {
allocN32Pixels(bitmapWidth, bitmapHeight)
}
val canvas = Canvas(bitmap)
canvas.drawImageRect(
image = image,
src = rect.toSkiaRect(),
dst = org.jetbrains.skia.Rect.makeWH(bitmapWidth.toFloat(), bitmapHeight.toFloat())
)
return bitmap.asComposeImageBitmap()
}
}
================================================
FILE: scale-zoomable-view/.gitignore
================================================
/build
================================================
FILE: scale-zoomable-view/build.gradle.kts
================================================
import scale.compileSdk
import scale.minSdk
plugins {
id("com.android.kotlin.multiplatform.library")
id("org.jetbrains.kotlin.plugin.compose")
id("org.jetbrains.kotlin.multiplatform")
id("com.vanniktech.maven.publish")
id("org.jetbrains.compose")
id("org.jetbrains.dokka")
}
kotlin {
androidLibrary {
namespace = "com.jvziyaoyao.scale.zoomable"
compileSdk = project.compileSdk
minSdk = project.minSdk
}
jvm()
val xcfName = "zoomableViewKit"
iosX64 {
binaries.framework {
baseName = xcfName
}
}
iosArm64 {
binaries.framework {
baseName = xcfName
}
}
iosSimulatorArm64 {
binaries.framework {
baseName = xcfName
}
}
sourceSets {
commonMain {
dependencies {
implementation(libs.kotlin.stdlib)
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.ui)
implementation(compose.components.resources)
implementation(compose.components.uiToolingPreview)
implementation(libs.org.jetbrains.kotlinx.datetime)
}
}
commonTest {
dependencies {
implementation(libs.kotlin.test)
}
}
androidMain {
dependencies {}
}
iosMain {
dependencies {}
}
}
}
================================================
FILE: scale-zoomable-view/gradle.properties
================================================
POM_ARTIFACT_ID=zoomable-view
POM_NAME=zoomable-view
POM_PACKAGING=aar
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/pager/Pager.kt
================================================
package com.jvziyaoyao.scale.zoomable.pager
import androidx.compose.foundation.gestures.TargetedFlingBehavior
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerDefaults
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2022-10-05 21:41
**/
/**
* 基于HorizonPager封装的pager组件
*
* @property pagerState 可以用来控制页面切换和获取页面状态等
*/
open class SupportedPagerState(
val pagerState: PagerState,
) {
/**
* 当前页码
*/
val currentPage: Int
get() = pagerState.currentPage
/**
* 目标页码
*/
val targetPage: Int
get() = pagerState.targetPage
/**
* 当前页数
*/
val pageCount: Int
get() = pagerState.pageCount
/**
* interactionSource
*/
val interactionSource: InteractionSource
get() = pagerState.interactionSource
/**
* 滚动到指定页面
*/
suspend fun scrollToPage(
// 指定的页码 @IntRange(from = 0)
page: Int,
// 滚动偏移量 @FloatRange(from = 0.0, to = 1.0)
pageOffset: Float = 0f,
) = pagerState.scrollToPage(page, pageOffset)
/**
* 动画滚动到指定页面
*/
suspend fun animateScrollToPage(
// 指定的页码 @IntRange(from = 0)
page: Int,
// 滚动偏移量 @FloatRange(from = 0.0, to = 1.0)
pageOffset: Float = 0f,
) = pagerState.animateScrollToPage(page, pageOffset)
}
/**
* 用于获取pager状态和控制pager
*
* @param initialPage 初始页码
* @param pageCount 总页数
* @return 返回一个通用对PagerState
*/
@Composable
fun rememberSupportedPagerState(
// 默认显示的页码 @IntRange(from = 0)
initialPage: Int = 0,
pageCount: () -> Int,
): SupportedPagerState {
val pageState = rememberPagerState(initialPage = initialPage, pageCount = pageCount)
return remember {
SupportedPagerState(pageState)
}
}
/**
* 切换页面对时候默认对手势效果
*
* @param pagerState 页面状态对象
* @return TargetedFlingBehavior
*/
@Composable
fun defaultFlingBehavior(pagerState: SupportedPagerState): TargetedFlingBehavior {
return PagerDefaults.flingBehavior(
state = pagerState.pagerState,
)
}
/**
* 一个通用pager组件,对底层对pager进行了封装
*
* @param modifier 图层修饰
* @param state pager状态获取与控制
* @param itemSpacing 每个item之间的间隔
* @param beyondViewportPageCount 页面外缓存个数
* @param userScrollEnabled 是否允许页面滚动
* @param flingBehavior 手势效果
* @param content 页面内容
*/
@Composable
fun SupportedHorizonPager(
modifier: Modifier = Modifier,
state: SupportedPagerState,
itemSpacing: Dp = 0.dp,
beyondViewportPageCount: Int = 0,
userScrollEnabled: Boolean = true,
flingBehavior: TargetedFlingBehavior = defaultFlingBehavior(state),
content: @Composable (page: Int) -> Unit,
) {
HorizontalPager(
state = state.pagerState,
modifier = modifier,
pageSpacing = itemSpacing,
beyondViewportPageCount = beyondViewportPageCount,
userScrollEnabled = userScrollEnabled,
flingBehavior = flingBehavior,
) { page ->
content(page)
}
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/pager/ZoomablePager.kt
================================================
package com.jvziyaoyao.scale.zoomable.pager
import androidx.compose.foundation.gestures.TargetedFlingBehavior
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableGestureScope
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableView
import com.jvziyaoyao.scale.zoomable.zoomable.ZoomableViewState
import com.jvziyaoyao.scale.zoomable.zoomable.rememberZoomableState
import kotlinx.coroutines.launch
/**
* @program: ZoomablePager
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-12-06 20:48
**/
// 图片间的默认间隔
val DEFAULT_ITEM_SPACE = 12.dp
// 页面外缓存个数
const val DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT = 1
/**
* 在ZoomablePager中对ZoomableView图层进行修饰对对象
*
*/
fun interface PagerZoomablePolicyScope {
@Composable
fun ZoomablePolicy(
intrinsicSize: Size,
content: @Composable (ZoomableViewState) -> Unit,
)
}
/**
* 用于获取ZoomablePager的状态和对其进行控制
*
* @property pagerState 底层SupportedPagerState
*/
open class ZoomablePagerState(
val pagerState: SupportedPagerState,
) {
/**
* 当前viewer的状态
*/
val zoomableViewState = mutableStateOf(null)
/**
* 当前页码
*/
val currentPage: Int
get() = pagerState.currentPage
/**
* 目标页码
*/
val targetPage: Int
get() = pagerState.targetPage
/**
* interactionSource
*/
val interactionSource: InteractionSource
get() = pagerState.interactionSource
/**
* 滚动到指定页面
* @param page Int
* @param pageOffset Float
*/
suspend fun scrollToPage(
// @IntRange(from = 0)
page: Int,
// @FloatRange(from = 0.0, to = 1.0)
pageOffset: Float = 0f,
) = pagerState.scrollToPage(page, pageOffset)
/**
* 动画滚动到指定页面
* @param page Int
* @param pageOffset Float
*/
suspend fun animateScrollToPage(
// @IntRange(from = 0)
page: Int,
// @FloatRange(from = 0.0, to = 1.0)
pageOffset: Float = 0f,
) = pagerState.animateScrollToPage(page, pageOffset)
}
/**
* 在Compose中获取一个ZoomablePagerState
*
* @param initialPage 初始页码
* @param pageCount 总页数
* @return
*/
@Composable
fun rememberZoomablePagerState(
// @IntRange(from = 0)
initialPage: Int = 0,
pageCount: () -> Int,
): ZoomablePagerState {
val zoomablePagerState = rememberSupportedPagerState(initialPage, pageCount)
return remember { ZoomablePagerState(zoomablePagerState) }
}
/**
* Pager的点击事件监听对象
*
* @property onTap 点击事件
* @property onDoubleTap 双击事件
* @property onLongPress 长按事件
*/
class PagerGestureScope(
var onTap: () -> Unit = {},
var onDoubleTap: () -> Boolean = { false },
var onLongPress: () -> Unit = {},
)
/**
* 基于Pager和ZoomableView实现的一个图片查看列表组件
*
* @param modifier 图层修饰
* @param state pager状态获取与控制
* @param itemSpacing 每张图片之间的间隔
* @param beyondViewportPageCount 页面外缓存个数
* @param flingBehavior 手势效果
* @param userScrollEnabled 是否允许页面滚动
* @param detectGesture 检测手势
* @param zoomablePolicy 图层本体
*/
@Composable
fun ZoomablePager(
modifier: Modifier = Modifier,
state: ZoomablePagerState,
itemSpacing: Dp = DEFAULT_ITEM_SPACE,
beyondViewportPageCount: Int = DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT,
flingBehavior: TargetedFlingBehavior = defaultFlingBehavior(state.pagerState),
userScrollEnabled: Boolean = true,
detectGesture: PagerGestureScope = PagerGestureScope(),
zoomablePolicy: @Composable PagerZoomablePolicyScope.(page: Int) -> Unit,
) {
val scope = rememberCoroutineScope()
// 确保不会越界
SupportedHorizonPager(
state = state.pagerState,
modifier = modifier
.fillMaxSize(),
itemSpacing = itemSpacing,
beyondViewportPageCount = beyondViewportPageCount,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled,
) { page ->
Box(modifier = Modifier.fillMaxSize()) {
PagerZoomablePolicyScope { intrinsicSize, content ->
val zoomableState = rememberZoomableState(contentSize = intrinsicSize)
LaunchedEffect(key1 = state.currentPage, key2 = zoomableState) {
if (state.currentPage == page) {
state.zoomableViewState.value = zoomableState
} else {
zoomableState.reset()
}
}
ZoomableView(
state = zoomableState,
boundClip = false,
detectGesture = ZoomableGestureScope(
onTap = { detectGesture.onTap() },
onDoubleTap = {
val consumed = detectGesture.onDoubleTap()
if (!consumed) scope.launch {
zoomableState.toggleScale(it)
}
},
onLongPress = { detectGesture.onLongPress() },
)
) {
content(zoomableState)
}
}.zoomablePolicy(page)
}
}
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/previewer/DraggablePreviewer.kt
================================================
package com.jvziyaoyao.scale.zoomable.previewer
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_ITEM_SPACE
import com.jvziyaoyao.scale.zoomable.pager.PagerGestureScope
import com.jvziyaoyao.scale.zoomable.pager.PagerZoomablePolicyScope
import com.jvziyaoyao.scale.zoomable.pager.SupportedPagerState
import com.jvziyaoyao.scale.zoomable.util.DrawText
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-12-25 10:29
**/
// 默认下拉关闭缩放阈值
const val DEFAULT_SCALE_TO_CLOSE_MIN_VALUE = 0.9F
/**
* 垂直手势的类型
*
*/
enum class VerticalDragType {
// 不开启垂直手势
None,
// 仅开启下拉手势
Down,
// 支持上下拉手势
UpAndDown,
;
}
/**
* 拖拉拽状态与控制
*
* @property scope 协程作用域
* @constructor
*
* @param defaultAnimationSpec 默认动画窗格
* @param verticalDragType 开启垂直手势的类型
* @param scaleToCloseMinValue 下拉关闭的缩小的阈值
* @param pagerState 预览状态
* @param itemStateMap 用于获取transformItemState
* @param getKey 获取当前key
*/
open class DraggablePreviewerState(
private val scope: CoroutineScope,
defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
verticalDragType: VerticalDragType = VerticalDragType.None,
scaleToCloseMinValue: Float = DEFAULT_SCALE_TO_CLOSE_MIN_VALUE,
pagerState: SupportedPagerState,
itemStateMap: ItemStateMap,
getKey: (Int) -> Any,
) : TransformPreviewerState(
scope, defaultAnimationSpec, pagerState, itemStateMap, getKey
) {
/**
* 开启垂直手势的类型
*/
private var verticalDragType by mutableStateOf(verticalDragType)
/**
* 下拉关闭的缩放的阈值,当scale小于这个值,就关闭,否则还原
*/
private var scaleToCloseMinValue by mutableStateOf(scaleToCloseMinValue)
/**
* 下拉关闭容器状态
*/
val draggableContainerState = DraggableContainerState(
defaultAnimationSpec = defaultAnimationSpec
)
suspend fun verticalDrag(pointerInputScope: PointerInputScope) {
pointerInputScope.apply {
// 记录开始时的位置
var startOffset by mutableStateOf(null)
// 标记是否为下拉关闭
var orientationDown by mutableStateOf(null)
// 如果getKay不为空才开始检测手势
if (verticalDragType != VerticalDragType.None) detectDragGestures(
onDragStart = OnDragStart@{
val zoomableState = zoomableViewState.value
if (zoomableState != null) {
// 只有viewer的缩放率为1时才允许下拉手势
if (zoomableState.scale.value == 1F) {
startOffset = it
// 进入下拉手势时禁用viewer的手势
zoomableState.allowGestureInput = false
}
} else {
// 需要在预览图层正常显示的时候才允许手势
if (previewerAlpha.value == 1F) {
startOffset = it
}
}
},
onDragEnd = OnDragEnd@{
// 如果开始位置为空,就退出
if (startOffset == null) return@OnDragEnd
// 重置开始位置和方向
startOffset = null
orientationDown = null
// 解除viewer的手势输入限制
val zoomableState = zoomableViewState.value
zoomableState?.allowGestureInput = true
// 缩放小于阈值,执行关闭动画,大于就恢复原样
if (draggableContainerState.scale.value < scaleToCloseMinValue) {
scope.launch {
val itemState = findTransformItemByIndex(currentPage)
if (itemState != null) {
dragDownClose(itemState)
} else {
viewerContainerShrinkDown()
}
}
} else {
scope.launch {
decorationAlpha.snapTo(1F)
}
scope.launch {
draggableContainerState.reset()
}
}
},
onDrag = OnVerticalDrag@{ change, dragAmount ->
if (startOffset == null) return@OnVerticalDrag
if (orientationDown == null) orientationDown = dragAmount.y > 0
if (orientationDown == true || verticalDragType == VerticalDragType.UpAndDown) {
val offsetY = change.position.y - startOffset!!.y
val offsetX = change.position.x - startOffset!!.x
val containerHeight = containerSize.value.height
val scale = (containerHeight - offsetY.absoluteValue).div(
containerHeight
)
scope.launch {
decorationAlpha.snapTo(scale)
draggableContainerState.offsetX.snapTo(offsetX)
draggableContainerState.offsetY.snapTo(offsetY)
draggableContainerState.scale.snapTo(scale)
}
} else {
// 如果不是向上,就返还输入权,以免页面卡顿
val zoomableState = zoomableViewState.value
zoomableState?.allowGestureInput = true
}
}
)
}
}
/**
* 响应下拉关闭
*/
private suspend fun dragDownClose(itemState: TransformItemState) {
// 取消开启动画
cancelEnterTransform()
// 标记动作开始
stateCloseStart()
draggableContainerState.apply {
val displaySize =
if (itemState.intrinsicSize != null && itemState.intrinsicSize!!.isSpecified) {
getDisplaySize(itemState.intrinsicSize!!, containerSize.value)
} else {
getDisplaySize(containerSize.value, containerSize.value)
}
val centerX = containerSize.value.width.div(2)
val centerY = containerSize.value.height.div(2)
val nextSize = displaySize.times(scale.value)
val nextTargetX = centerX + offsetX.value - nextSize.width.div(2)
val nextTargetY = centerY + offsetY.value - nextSize.height.div(2)
displayWidth.snapTo(nextSize.width)
displayHeight.snapTo(nextSize.height)
displayOffsetX.snapTo(nextTargetX)
displayOffsetY.snapTo(nextTargetY)
}
// 启动关闭
exitFromCurrentState(itemState)
// 恢复原来的状态
draggableContainerState.resetImmediately()
// 标记动作结束
stateCloseEnd()
}
/**
* viewer容器缩小关闭
*/
private suspend fun viewerContainerShrinkDown(
animationSpec: AnimationSpec? = null
) {
val currentAnimationSpec = animationSpec ?: defaultAnimationSpec
// 标记动作开始
stateCloseStart()
coroutineScope {
listOf(
// 缩小容器
async {
draggableContainerState.scale.animateTo(
0F,
animationSpec = currentAnimationSpec
)
},
// 关闭UI
async {
decorationAlpha.animateTo(0F, animationSpec = currentAnimationSpec)
}
).awaitAll()
// 关闭动画组件
animateContainerVisibleState = MutableTransitionState(false)
// 有一些手机会出现闪烁问题
delay(24)
// 恢复原来的状态
draggableContainerState.resetImmediately()
// 标记动作结束
stateCloseEnd()
}
}
}
/**
* 变换动画容器的状态
*
* @property defaultAnimationSpec 默认动画窗格
*/
class DraggableContainerState(
var defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC
) {
// 容器的偏移量X
var offsetX = Animatable(0F)
// 容器的偏移量Y
var offsetY = Animatable(0F)
// 容器缩放
var scale = Animatable(1F)
/**
* 重置回原来的状态
* @param animationSpec AnimationSpec
*/
suspend fun reset(animationSpec: AnimationSpec = defaultAnimationSpec) {
coroutineScope {
listOf(
async {
offsetX.animateTo(0F, animationSpec)
},
async {
offsetY.animateTo(0F, animationSpec)
},
async {
scale.animateTo(1F, animationSpec)
},
).awaitAll()
}
}
/**
* 立刻重置
*/
suspend fun resetImmediately() {
offsetX.snapTo(0F)
offsetY.snapTo(0F)
scale.snapTo(1F)
}
}
/**
* 可拖拽释放的弹出预览组件
*
* @param modifier 图层修饰
* @param state 状态对象
* @param itemSpacing 图片间的间隔
* @param beyondViewportPageCount 页面外缓存个数
* @param enter 调用open时的进入动画
* @param exit 调用close时的退出动画
* @param debugMode 调试模式
* @param detectGesture 检测手势
* @param previewerLayer 容器的图层修饰
* @param zoomablePolicy 缩放图层的修饰
*/
@Composable
fun DraggablePreviewer(
modifier: Modifier = Modifier,
state: DraggablePreviewerState,
itemSpacing: Dp = DEFAULT_ITEM_SPACE,
beyondViewportPageCount: Int = DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT,
enter: EnterTransition = DEFAULT_PREVIEWER_ENTER_TRANSITION,
exit: ExitTransition = DEFAULT_PREVIEWER_EXIT_TRANSITION,
debugMode: Boolean = false,
detectGesture: PagerGestureScope = PagerGestureScope(),
previewerLayer: TransformLayerScope = TransformLayerScope(),
zoomablePolicy: @Composable PagerZoomablePolicyScope.(page: Int) -> Boolean,
) {
state.apply {
TransformPreviewer(
modifier = modifier,
state = state,
itemSpacing = itemSpacing,
beyondViewportPageCount = beyondViewportPageCount,
enter = enter,
exit = exit,
debugMode = debugMode,
detectGesture = detectGesture,
previewerLayer = TransformLayerScope(
previewerDecoration = { innerBox ->
val actionColor = Color.Yellow
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(getKey) {
verticalDrag(this)
}
.graphicsLayer {
translationX = draggableContainerState.offsetX.value
translationY = draggableContainerState.offsetY.value
scaleX = draggableContainerState.scale.value
scaleY = draggableContainerState.scale.value
}
.run {
if (debugMode) border(width = 2.dp, color = actionColor) else this
}
) {
previewerLayer.previewerDecoration {
innerBox()
}
if (debugMode) DrawText(
modifier = Modifier.align(Alignment.TopEnd),
text = "DraggablePreviewer",
color = actionColor,
)
}
},
background = previewerLayer.background,
foreground = previewerLayer.foreground,
),
zoomablePolicy = zoomablePolicy
)
}
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/previewer/PopupPreviewer.kt
================================================
package com.jvziyaoyao.scale.zoomable.previewer
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_ITEM_SPACE
import com.jvziyaoyao.scale.zoomable.pager.PagerGestureScope
import com.jvziyaoyao.scale.zoomable.pager.PagerZoomablePolicyScope
import com.jvziyaoyao.scale.zoomable.pager.SupportedPagerState
import com.jvziyaoyao.scale.zoomable.pager.ZoomablePager
import com.jvziyaoyao.scale.zoomable.pager.ZoomablePagerState
import com.jvziyaoyao.scale.zoomable.pager.rememberSupportedPagerState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* @program: PopupPreviewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-12-13 11:45
**/
/**
* 默认的弹出预览时的动画效果
*/
val DEFAULT_PREVIEWER_ENTER_TRANSITION =
scaleIn(tween(180)) + fadeIn(tween(240))
/**
* 默认的关闭预览时的动画效果
*/
val DEFAULT_PREVIEWER_EXIT_TRANSITION =
scaleOut(tween(320)) + fadeOut(tween(240))
/**
* Compose中获取一个PopupPreviewerState的方式
*
* @param initialPage 初始页码
* @param pageCount 总页数
* @return 返回一个PopupPreviewerState
*/
@Composable
fun rememberPopupPreviewerState(
// @IntRange(from = 0)
initialPage: Int = 0,
pageCount: () -> Int,
): PopupPreviewerState {
val pagerState = rememberSupportedPagerState(initialPage, pageCount)
return remember {
PopupPreviewerState(pagerState = pagerState)
}
}
/**
* 弹出预览状态与控制对象
*
* @constructor
*
* @param pagerState 封装的通用pagerState
*/
open class PopupPreviewerState(
pagerState: SupportedPagerState,
) : ZoomablePagerState(pagerState) {
// 锁对象
private var mutex = Mutex()
// 最外侧animateVisibleState
internal var animateContainerVisibleState by mutableStateOf(MutableTransitionState(false))
// 用于监听状态
internal var containerVisibleFlow = MutableStateFlow(false)
// 进入转换动画
internal var enterTransition: EnterTransition? = null
// 离开的转换动画
internal var exitTransition: ExitTransition? = null
// 标记打开动作,执行开始
internal suspend fun stateOpenStart() =
updateState(animating = true, visible = false, visibleTarget = true)
// 标记打开动作,执行结束
internal suspend fun stateOpenEnd() =
updateState(animating = false, visible = true, visibleTarget = null)
// 标记关闭动作,执行开始
internal suspend fun stateCloseStart() =
updateState(animating = true, visible = true, visibleTarget = false)
// 标记关闭动作,执行结束
internal suspend fun stateCloseEnd() =
updateState(animating = false, visible = false, visibleTarget = null)
// 是否正在进行动画
var animating by mutableStateOf(false)
internal set
// 是否可见
var visible by mutableStateOf(false)
internal set
// 是否可见的目标值
var visibleTarget by mutableStateOf(null)
internal set
// 是否允许执行open操作
val canOpen: Boolean
get() = !visible && visibleTarget == null && !animating
// 是否允许执行close操作
val canClose: Boolean
get() = visible && visibleTarget == null && !animating
/**
* 更新当前的标记状态
* @param animating Boolean
* @param visible Boolean
* @param visibleTarget Boolean?
*/
suspend fun updateState(animating: Boolean, visible: Boolean, visibleTarget: Boolean?) {
mutex.withLock {
this.animating = animating
this.visible = visible
this.visibleTarget = visibleTarget
}
}
open suspend fun openAction(
index: Int = 0,
enterTransition: EnterTransition? = null,
) {
// 设置当前转换动画
this.enterTransition = enterTransition
// container动画立即设置为关闭
animateContainerVisibleState = MutableTransitionState(false)
// 开启container
animateContainerVisibleState.targetState = true
// 滚动到指定页面
scrollToPage(index)
// 等状态变到目标值
containerVisibleFlow.takeWhile { !it }.collect {}
}
suspend fun open(
index: Int = 0,
enterTransition: EnterTransition? = null,
) {
// 标记状态
stateOpenStart()
// 实际业务发生
openAction(index, enterTransition)
// 标记状态
stateOpenEnd()
}
open suspend fun closeAction(
exitTransition: ExitTransition? = null,
) {
// 设置当前转换动画
this.exitTransition = exitTransition
// 这里创建一个全新的state是为了让exitTransition的设置得到响应
animateContainerVisibleState = MutableTransitionState(true)
// 开启container关闭动画
animateContainerVisibleState.targetState = false
// 等状态变到目标值
containerVisibleFlow.takeWhile { it }.collect {}
}
suspend fun close(
exitTransition: ExitTransition? = null,
) {
// 标记状态
stateCloseStart()
// 实际业务发生
closeAction(exitTransition)
// 标记状态
stateCloseEnd()
}
}
/**
* 基于Pager、ZoomableView实现的弹出预览组件
*
* @param modifier 图层修饰
* @param state 组件的状态与控制对象
* @param itemSpacing 图片间的间隔
* @param beyondViewportPageCount 页面外缓存个数
* @param enter 进入动画
* @param exit 退出动画
* @param detectGesture 检测手势
* @param previewerDecoration 外侧图层容器修饰
* @param zoomablePolicy ZoomableView图层修饰
*/
@Composable
fun PopupPreviewer(
modifier: Modifier = Modifier,
state: PopupPreviewerState,
itemSpacing: Dp = DEFAULT_ITEM_SPACE,
beyondViewportPageCount: Int = DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT,
enter: EnterTransition = DEFAULT_PREVIEWER_ENTER_TRANSITION,
exit: ExitTransition = DEFAULT_PREVIEWER_EXIT_TRANSITION,
detectGesture: PagerGestureScope = PagerGestureScope(),
previewerDecoration: @Composable (innerBox: @Composable () -> Unit) -> Unit =
@Composable { innerBox -> innerBox() },
zoomablePolicy: @Composable PagerZoomablePolicyScope.(page: Int) -> Unit,
) {
state.apply {
LaunchedEffect(animateContainerVisibleState.currentState) {
containerVisibleFlow.value = animateContainerVisibleState.currentState
}
AnimatedVisibility(
modifier = Modifier.fillMaxSize(),
visibleState = animateContainerVisibleState,
enter = enterTransition ?: enter,
exit = exitTransition ?: exit,
) {
previewerDecoration {
ZoomablePager(
modifier = modifier.fillMaxSize(),
state = state,
itemSpacing = itemSpacing,
beyondViewportPageCount = beyondViewportPageCount,
detectGesture = if (animating) PagerGestureScope() else detectGesture,
zoomablePolicy = zoomablePolicy,
// 正在动画中不允许页面滚动
userScrollEnabled = !animating
)
}
}
}
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/previewer/Previewer.kt
================================================
package com.jvziyaoyao.scale.zoomable.previewer
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_ITEM_SPACE
import com.jvziyaoyao.scale.zoomable.pager.PagerGestureScope
import com.jvziyaoyao.scale.zoomable.pager.PagerZoomablePolicyScope
import com.jvziyaoyao.scale.zoomable.pager.SupportedPagerState
import com.jvziyaoyao.scale.zoomable.pager.rememberSupportedPagerState
import kotlinx.coroutines.CoroutineScope
/**
* 获取一个图片预览的状态与控制对象
*
* @param scope 协程作用域
* @param defaultAnimationSpec 默认动画窗格
* @param initialPage 初始化页码
* @param verticalDragType 垂直手势类型
* @param transformItemStateMap 帮助Previewer获取转换动画的小图map
* @param pageCount 总页数
* @param getKey 获取某一页的索引key的方法
* @return 返回一个PreviewerState
*/
@Composable
fun rememberPreviewerState(
scope: CoroutineScope = rememberCoroutineScope(),
defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
initialPage: Int = 0,
verticalDragType: VerticalDragType = VerticalDragType.Down,
transformItemStateMap: ItemStateMap = mutableMapOf(),
pageCount: () -> Int,
getKey: (Int) -> Any = {},
): PreviewerState {
val pagerState = rememberSupportedPagerState(initialPage = initialPage, pageCount = pageCount)
val previewerState = remember {
PreviewerState(
scope = scope,
verticalDragType = verticalDragType,
pagerState = pagerState,
itemStateMap = transformItemStateMap,
getKey = getKey,
)
}
previewerState.defaultAnimationSpec = defaultAnimationSpec
return previewerState
}
/**
* 图片预览的状态与控制对象
*
* @constructor
*
* @param scope 协程作用域
* @param defaultAnimationSpec 默认动画窗格
* @param verticalDragType 垂直手势类型
* @param scaleToCloseMinValue 下拉关闭的缩小的阈值
* @param pagerState 预览状态
* @param itemStateMap 用于获取transformItemState
* @param getKey 获取当前key的方法
*/
class PreviewerState(
scope: CoroutineScope,
defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
verticalDragType: VerticalDragType = VerticalDragType.None,
scaleToCloseMinValue: Float = DEFAULT_SCALE_TO_CLOSE_MIN_VALUE,
pagerState: SupportedPagerState,
itemStateMap: ItemStateMap,
getKey: (Int) -> Any,
) : DraggablePreviewerState(
scope,
defaultAnimationSpec,
verticalDragType,
scaleToCloseMinValue,
pagerState,
itemStateMap,
getKey
)
/**
* 带转换效果的图片弹出预览组件
*
* @param modifier 图层修饰
* @param state 状态对象
* @param itemSpacing 图片间的间隔
* @param beyondViewportPageCount 页面外缓存个数
* @param enter 调用open时的进入动画
* @param exit 调用close时的退出动画
* @param debugMode 调试模式
* @param detectGesture 检测手势
* @param previewerLayer 容器的图层修饰
* @param zoomablePolicy 缩放图层的修饰
*/
@Composable
fun Previewer(
// 编辑参数
modifier: Modifier = Modifier,
// 状态对象
state: PreviewerState,
// 图片间的间隔
itemSpacing: Dp = DEFAULT_ITEM_SPACE,
// 页面外缓存个数
beyondViewportPageCount: Int = DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT,
// 进入动画
enter: EnterTransition = DEFAULT_PREVIEWER_ENTER_TRANSITION,
// 退出动画
exit: ExitTransition = DEFAULT_PREVIEWER_EXIT_TRANSITION,
// 调试模式
debugMode: Boolean = false,
// 检测手势
detectGesture: PagerGestureScope = PagerGestureScope(),
// 图层修饰
previewerLayer: TransformLayerScope = TransformLayerScope(),
// 缩放图层
zoomablePolicy: @Composable PagerZoomablePolicyScope.(page: Int) -> Boolean,
) {
DraggablePreviewer(
modifier = modifier,
state = state,
itemSpacing = itemSpacing,
beyondViewportPageCount = beyondViewportPageCount,
enter = enter,
exit = exit,
debugMode = debugMode,
detectGesture = detectGesture,
previewerLayer = previewerLayer,
zoomablePolicy = zoomablePolicy,
)
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/previewer/TransformItem.kt
================================================
package com.jvziyaoyao.scale.zoomable.previewer
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.unit.IntSize
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
typealias ItemStateMap = MutableMap
/**
* 在compose中获取一个TransformItemState的方式
*
* @param scope 协程作用域
* @param checkInBound 判断当前图片是否在显示范围内,可以为空
* @param intrinsicSize 图片的固有大小,必须要有值且确定才能正常显示
* @return TransformItemState
*/
@Composable
fun rememberTransformItemState(
scope: CoroutineScope = rememberCoroutineScope(),
checkInBound: (TransformItemState.() -> Boolean)? = null,
intrinsicSize: Size? = null,
): TransformItemState {
val transformItemState =
remember {
TransformItemState(
scope = scope,
checkInBound = checkInBound,
)
}
transformItemState.intrinsicSize = intrinsicSize
return transformItemState
}
/**
* TransformItem的状态与控制对象
*
* @property key 当前TransformItem的唯一标识
* @property blockCompose 实际TransformItem中显示的内容
* @property scope 协程作用域
* @property blockPosition TransformItem的绝对位置
* @property blockSize TransformItem的大小
* @property intrinsicSize 传入blockCompose的固有大小
* @property checkInBound 判断当前TransformItem是否在显示范围内的方法
*/
class TransformItemState(
var key: Any = Unit,
var blockCompose: (@Composable (Any) -> Unit) = {},
var scope: CoroutineScope,
var blockPosition: Offset = Offset.Zero,
var blockSize: IntSize = IntSize.Zero,
var intrinsicSize: Size? = null,
var checkInBound: (TransformItemState.() -> Boolean)? = null,
) {
private fun checkItemInMap(itemMap: ItemStateMap) {
if (checkInBound == null) return
if (checkInBound!!.invoke(this)) {
addItem(itemMap = itemMap)
} else {
removeItem(itemMap = itemMap)
}
}
/**
* 位置和大小发生变化时
* @param position Offset
* @param size IntSize
*/
internal fun onPositionChange(position: Offset, size: IntSize, itemMap: ItemStateMap) {
blockPosition = position
blockSize = size
scope.launch {
checkItemInMap(itemMap)
}
}
/**
* 判断item是否在所需范围内,返回true,则添加该item到map,返回false则移除
* @param checkInBound Function0
*/
fun checkIfInBound(itemMap: ItemStateMap, checkInBound: () -> Boolean) {
if (checkInBound()) {
addItem(itemMap = itemMap)
} else {
removeItem(itemMap = itemMap)
}
}
/**
* 添加item到map上
* @param key Any?
*/
fun addItem(key: Any? = null, itemMap: ItemStateMap) {
// TODO mutex
val currentKey = key ?: this.key
if (checkInBound != null) return
itemMap[currentKey] = this
}
/**
* 从map上移除item
* @param key Any?
*/
fun removeItem(key: Any? = null, itemMap: ItemStateMap) {
// TODO mutex
val currentKey = key ?: this.key
if (checkInBound != null) return
itemMap.remove(currentKey)
}
}
/**
* 用于实现Previewer变换效果的小图装载容器
*
* @param modifier 图层修饰
* @param key 唯一标识
* @param itemState 该组件的状态与控制对象
* @param itemVisible 该组件的可见性
* @param content 需要显示的实际内容
*/
@Composable
fun TransformItemView(
modifier: Modifier = Modifier,
key: Any,
itemState: TransformItemState = rememberTransformItemState(),
itemStateMap: ItemStateMap,
itemVisible: Boolean,
content: @Composable (Any) -> Unit,
) {
val scope = rememberCoroutineScope()
itemState.key = key
itemState.blockCompose = content
DisposableEffect(key) {
// 这个composable加载时添加到map
scope.launch {
itemState.addItem(itemMap = itemStateMap)
}
onDispose {
// composable退出时从map移除
itemState.removeItem(itemMap = itemStateMap)
}
}
Box(
modifier = modifier
.onGloballyPositioned {
itemState.onPositionChange(
position = it.positionInRoot(),
size = it.size,
itemMap = itemStateMap,
)
}
.fillMaxSize()
) {
if (itemVisible) {
itemState.blockCompose(key)
}
}
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/previewer/TransformPreviewer.kt
================================================
package com.jvziyaoyao.scale.zoomable.previewer
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.toSize
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT
import com.jvziyaoyao.scale.zoomable.pager.DEFAULT_ITEM_SPACE
import com.jvziyaoyao.scale.zoomable.pager.PagerGestureScope
import com.jvziyaoyao.scale.zoomable.pager.PagerZoomablePolicyScope
import com.jvziyaoyao.scale.zoomable.pager.SupportedPagerState
import com.jvziyaoyao.scale.zoomable.util.DrawText
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
// 比较轻柔的动画窗格
val DEFAULT_SOFT_ANIMATION_SPEC = tween(400)
/**
* @program: TransformPreviewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-12-11 20:21
**/
/**
* 用于控制转换效果图层与图片列表浏览图层
*
* @property scope 协程作用域
* @property defaultAnimationSpec 默认动画窗格
* @property itemStateMap 用于获取transformItemState
* @property getKey 根据下标获取唯一标识的方法
* @constructor
*
* @param pagerState
*/
open class TransformPreviewerState(
// 协程作用域
private val scope: CoroutineScope,
// 默认动画窗格
var defaultAnimationSpec: AnimationSpec = DEFAULT_SOFT_ANIMATION_SPEC,
// 预览状态
pagerState: SupportedPagerState,
// 用于获取transformItemState
val itemStateMap: ItemStateMap,
// 获取当前key
val getKey: (Int) -> Any,
) : PopupPreviewerState(pagerState) {
val itemContentVisible = mutableStateOf(false)
val containerSize = mutableStateOf(Size.Zero)
val displayWidth = Animatable(0F)
val displayHeight = Animatable(0F)
val displayOffsetX = Animatable(0F)
val displayOffsetY = Animatable(0F)
// 查找key关联的transformItem
private fun findTransformItem(key: Any): TransformItemState? {
return itemStateMap[key]
}
// 根据index查询key
fun findTransformItemByIndex(index: Int): TransformItemState? {
val key = getKey(index)
return findTransformItem(key)
}
val enterIndex = mutableStateOf(null)
val mountedFlow = MutableStateFlow(false)
val decorationAlpha = Animatable(0F)
val previewerAlpha = Animatable(0F)
private suspend fun awaitMounted() {
mountedFlow.takeWhile { !it }.collect { }
}
private suspend fun enterTransformInternal(
index: Int,
animationSpec: AnimationSpec? = null
) {
val currentAnimationSpec = animationSpec ?: defaultAnimationSpec
val itemState = findTransformItemByIndex(index)
if (itemState != null) {
itemState.apply {
stateOpenStart()
mountedFlow.value = false
enterIndex.value = index
// 设置动画开始的位置
displayWidth.snapTo(blockSize.width.toFloat())
displayHeight.snapTo(blockSize.height.toFloat())
displayOffsetX.snapTo(blockPosition.x)
displayOffsetY.snapTo(blockPosition.y)
itemContentVisible.value = true
// 关闭修饰图层
decorationAlpha.snapTo(0F)
previewerAlpha.snapTo(0F)
// 开启viewer图层
animateContainerVisibleState = MutableTransitionState(true)
val displaySize = if (intrinsicSize != null && intrinsicSize!!.isSpecified) {
getDisplaySize(intrinsicSize!!, containerSize.value)
} else {
getDisplaySize(containerSize.value, containerSize.value)
}
// val displaySize = getDisplaySize(intrinsicSize ?: Size.Zero, containerSize.value)
val targetX = (containerSize.value.width - displaySize.width).div(2)
val targetY = (containerSize.value.height - displaySize.height).div(2)
// val animationSpec = tween(600)f
try {
listOf(
scope.async {
decorationAlpha.animateTo(1F, currentAnimationSpec)
},
scope.async {
displayWidth.animateTo(displaySize.width, currentAnimationSpec)
},
scope.async {
displayHeight.animateTo(displaySize.height, currentAnimationSpec)
},
scope.async {
displayOffsetX.animateTo(targetX, currentAnimationSpec)
},
scope.async {
displayOffsetY.animateTo(targetY, currentAnimationSpec)
},
).awaitAll()
} catch (e: Exception) {
e.printStackTrace()
}
previewerAlpha.snapTo(1F)
updateState(animating = false, visible = false, visibleTarget = true)
val alreadyScroll2Current = try {
// 切换页面到index
pagerState.scrollToPage(index)
true
} catch (e: Exception) {
e.printStackTrace()
false
}
// 25/6/25 在加载结束前标记动画结束
updateState(animating = false, visible = true, visibleTarget = null)
// 等待挂载成功
if (alreadyScroll2Current) awaitMounted()
// 动画结束,开启预览
itemContentVisible.value = false
// 恢复
enterIndex.value = null
// 25/6/25 在加载结束前标记动画结束
// updateState(animating = false, visible = true, visibleTarget = null)
}
} else {
open(index)
}
}
private var enterTransformJob: Job? = null
suspend fun enterTransform(
index: Int,
animationSpec: AnimationSpec? = null,
) {
enterTransformJob = scope.launch {
enterTransformInternal(index, animationSpec)
}
enterTransformJob?.join()
}
internal fun cancelEnterTransform() {
enterTransformJob?.cancel()
enterIndex.value = null
}
suspend fun exitTransform(animationSpec: AnimationSpec? = null) {
// 取消开启动画
cancelEnterTransform()
// 获取当前页码
val index = currentPage
// 同步动画开始的位置
val itemState = findTransformItemByIndex(index)
if (itemState != null && itemState.blockSize != IntSize.Zero) {
itemState.apply {
stateCloseStart()
val displaySize = getDisplaySize(intrinsicSize ?: Size.Zero, containerSize.value)
val displayX = (containerSize.value.width - displaySize.width).div(2)
val displayY = (containerSize.value.height - displaySize.height).div(2)
var targetSize = displaySize
var targetX = displayX
var targetY = displayY
zoomableViewState.value?.apply {
targetSize = displaySize * scale.value
targetX =
offsetX.value + displayX - (targetSize.width - displaySize.width).div(2)
targetY =
offsetY.value + displayY - (targetSize.height - displaySize.height).div(2)
}
displayWidth.snapTo(targetSize.width)
displayHeight.snapTo(targetSize.height)
displayOffsetX.snapTo(targetX)
displayOffsetY.snapTo(targetY)
// 启动关闭
exitFromCurrentState(itemState, animationSpec)
stateCloseEnd()
}
} else {
close()
}
}
internal suspend fun exitFromCurrentState(
itemState: TransformItemState,
animationSpec: AnimationSpec? = null,
) {
val currentAnimationSpec = animationSpec ?: defaultAnimationSpec
// 动画结束,开启预览
itemContentVisible.value = true
// 关闭viewer图层
previewerAlpha.snapTo(0F)
try {
itemState.apply {
listOf(
scope.async {
decorationAlpha.animateTo(0F, currentAnimationSpec)
},
scope.async {
displayWidth.animateTo(blockSize.width.toFloat(), currentAnimationSpec)
},
scope.async {
displayHeight.animateTo(blockSize.height.toFloat(), currentAnimationSpec)
},
scope.async {
displayOffsetX.animateTo(blockPosition.x, currentAnimationSpec)
},
scope.async {
displayOffsetY.animateTo(blockPosition.y, currentAnimationSpec)
},
).awaitAll()
}
} catch (e: Exception) {
e.printStackTrace()
}
// 关闭viewer图层
animateContainerVisibleState = MutableTransitionState(false)
// 关闭图层
itemContentVisible.value = false
}
override suspend fun openAction(
index: Int,
enterTransition: EnterTransition?,
) {
// 显示修饰图层
decorationAlpha.snapTo(1F)
previewerAlpha.snapTo(1F)
super.openAction(index, enterTransition)
}
}
/**
* 获取一个组件在容器中完全显示时的大小
*
* @param contentSize 组件的固有大小
* @param containerSize 容器大小
* @return 返回显示的大小
*/
fun getDisplaySize(contentSize: Size, containerSize: Size): Size {
val containerRatio = containerSize.run {
width.div(height)
}
val contentRatio = contentSize.run {
width.div(height)
}
val widthFixed = contentRatio > containerRatio
val scale1x = if (widthFixed) {
containerSize.width.div(contentSize.width)
} else {
containerSize.height.div(contentSize.height)
}
return Size(
width = contentSize.width.times(scale1x),
height = contentSize.height.times(scale1x),
)
}
/**
* 转换过程中的转换动效图层
*
* @param state 用于控制转换效果图层与图片列表浏览图层
* @param debugMode 调试模式
*/
@Composable
fun TransformContentLayer(
state: TransformPreviewerState,
debugMode: Boolean = false,
) {
LocalDensity.current.apply {
state.apply {
BoxWithConstraints(
modifier = Modifier.fillMaxSize()
) {
val maxWidthPx = maxWidth.toPx()
val maxHeightPx = maxHeight.toPx()
val fitSize = getDisplaySize(
containerSize = Size(maxWidthPx, maxHeightPx),
contentSize = Size(displayWidth.value, displayHeight.value),
)
if (fitSize.isSpecified) {
val targetScaleX = displayWidth.value.div(fitSize.width)
val targetScaleY = displayHeight.value.div(fitSize.height)
val actionColor = Color.Green
Box(
modifier = Modifier
.graphicsLayer {
scaleX = targetScaleX
scaleY = targetScaleY
translationX = displayOffsetX.value
translationY = displayOffsetY.value
transformOrigin = TransformOrigin(0F, 0F)
}
.size(
width = fitSize.width.toDp(),
height = fitSize.height.toDp()
)
.run {
if (debugMode) border(width = 2.dp, color = actionColor) else this
}
) {
val item = findTransformItemByIndex(enterIndex.value ?: currentPage)
item?.blockCompose?.invoke(item.key)
if (debugMode) DrawText(text = "Transform", color = actionColor)
}
} else {
if (debugMode) DrawText(text = "FitSize unspecified", color = Color.Yellow)
}
}
}
}
}
/**
* 转换效果在切换到实际显示图层前的占位图层
*
* @param page 当前页码
* @param state 图层控制对象
* @param debugMode 是否处于调试模式
*/
@Composable
fun TransformContentForPage(
page: Int,
state: TransformPreviewerState,
debugMode: Boolean = false,
) {
state.apply {
val density = LocalDensity.current
val item = findTransformItemByIndex(page)
BoxWithConstraints(
modifier = Modifier
.fillMaxSize()
) {
density.apply {
item?.apply {
val containerSize = Size(maxWidth.toPx(), maxHeight.toPx())
intrinsicSize?.run {
if (isSpecified) Size(width, height) else containerSize
}?.let { contentSize ->
val displaySize = getDisplaySize(
containerSize = containerSize,
contentSize = contentSize,
)
val actionColor = Color.Cyan
Box(
modifier = Modifier
.size(
width = displaySize.width.toDp(),
height = displaySize.height.toDp(),
)
.run {
if (debugMode) border(
width = 2.dp,
color = actionColor
) else this
}
.align(Alignment.Center),
) {
blockCompose.invoke(item.key)
if (debugMode) DrawText(text = "TransformForPage", color = actionColor)
}
}
}
}
}
}
}
/**
* 通过这个对象可以自定义预览图层
*
* @property previewerDecoration 图层修饰
* @property background 背景图层
* @property foreground 前景图层
*/
class TransformLayerScope(
var previewerDecoration: @Composable (innerBox: @Composable () -> Unit) -> Unit =
@Composable { innerBox -> innerBox() },
var background: @Composable () -> Unit = {},
var foreground: @Composable () -> Unit = {},
)
/**
* 支持弹出转换动画的图片预览组件
*
* @param modifier 图层修饰
* @param state 状态对象
* @param itemSpacing 图片间的间隔
* @param beyondViewportPageCount 页面外缓存个数
* @param enter 调用open时的进入动画
* @param exit 调用close时的退出动画
* @param debugMode 调试模式
* @param detectGesture 检测手势
* @param previewerLayer 容器的图层修饰
* @param zoomablePolicy 缩放图层的修饰
*/
@Composable
fun TransformPreviewer(
modifier: Modifier = Modifier,
state: TransformPreviewerState,
itemSpacing: Dp = DEFAULT_ITEM_SPACE,
beyondViewportPageCount: Int = DEFAULT_BEYOND_VIEWPORT_ITEM_COUNT,
enter: EnterTransition = DEFAULT_PREVIEWER_ENTER_TRANSITION,
exit: ExitTransition = DEFAULT_PREVIEWER_EXIT_TRANSITION,
debugMode: Boolean = false,
detectGesture: PagerGestureScope = PagerGestureScope(),
previewerLayer: TransformLayerScope = TransformLayerScope(),
zoomablePolicy: @Composable PagerZoomablePolicyScope.(page: Int) -> Boolean,
) {
state.apply {
Box(
modifier = modifier
.fillMaxSize()
.onSizeChanged {
containerSize.value = it.toSize()
}) {
PopupPreviewer(
modifier = modifier.fillMaxSize(),
state = this@apply,
detectGesture = detectGesture,
enter = enter,
exit = exit,
itemSpacing = itemSpacing,
beyondViewportPageCount = beyondViewportPageCount,
zoomablePolicy = { page ->
Box(modifier = Modifier.fillMaxSize()) {
val zoomableMounted = remember { mutableStateOf(false) }
if (!zoomableMounted.value) {
TransformContentForPage(
page = page,
state = state,
debugMode = debugMode
)
}
zoomableMounted.value = zoomablePolicy(page)
LaunchedEffect(zoomableMounted.value) {
// Log.i(
// "TAG",
// "TransformBody TransformPreviewer: ${enterIndex.value == page} ~ ${zoomableMounted.value} ~ $page"
// )
if (enterIndex.value == page && zoomableMounted.value) {
// delay(1000)
mountedFlow.emit(true)
}
}
// 如果等待mounted时间很久,用户切换页面过快导致开启的页面被移除
DisposableEffect(Unit) {
onDispose {
if (enterIndex.value == page && zoomableMounted.value) {
if (!mountedFlow.value) {
mountedFlow.value = true
}
}
}
}
}
},
previewerDecoration = { innerBox ->
@Composable
fun capsuleLayer(content: @Composable () -> Unit) {
Box(
modifier = Modifier
.alpha(decorationAlpha.value)
) { content() }
}
previewerLayer.apply {
capsuleLayer { background() }
previewerDecoration {
Box(
modifier = Modifier
.fillMaxSize()
.alpha(previewerAlpha.value)
) {
innerBox()
}
}
capsuleLayer { foreground() }
}
}
)
if (itemContentVisible.value && previewerAlpha.value != 1F) {
TransformContentLayer(state = state, debugMode = debugMode)
}
}
}
}
/**
* 用于实现Previewer变换效果的小图装载容器
*
* @param modifier 图层修饰
* @param key 唯一标识
* @param itemState 该组件的状态与控制对象
* @param transformState 预览组件的状态与控制对象
* @param content 需要显示的实际内容
*/
@Composable
fun TransformItemView(
modifier: Modifier = Modifier,
key: Any,
itemState: TransformItemState = rememberTransformItemState(),
transformState: TransformPreviewerState,
content: @Composable (Any) -> Unit,
) {
transformState.apply {
val currentPageKey = try {
getKey(currentPage)
} catch (e: Exception) {
null
}
val isCurrentPage = currentPageKey != key
TransformItemView(
modifier = modifier,
key = key,
itemState = itemState,
itemStateMap = transformState.itemStateMap,
itemVisible = if (!itemContentVisible.value) {
if (previewerAlpha.value == 1F) {
if (!visible) true else isCurrentPage
} else true
} else {
if (previewerAlpha.value == 1F) {
isCurrentPage
} else {
if (enterIndex.value != null) {
getKey(enterIndex.value!!) != key
} else isCurrentPage
}
},
content = content,
)
}
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/util/TextUtil.kt
================================================
package com.jvziyaoyao.scale.zoomable.util
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
@Composable
fun DrawText(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Black,
fontSize: TextUnit = 16.sp,
) {
val textMeasurer = rememberTextMeasurer()
BoxWithConstraints(modifier = modifier) {
val layoutResult = textMeasurer.measure(
text = text,
style = TextStyle(
color = color,
fontSize = fontSize,
)
)
Canvas(modifier = Modifier.fillMaxSize()) {
drawText(layoutResult)
}
}
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/util/TimeUtil.kt
================================================
package com.jvziyaoyao.scale.zoomable.util
import kotlin.time.Clock
import kotlin.time.ExperimentalTime
@OptIn(ExperimentalTime::class)
fun getMilliseconds(): Long {
return Clock.System.now().toEpochMilliseconds()
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/zoomable/ZoomableGesture.kt
================================================
package com.jvziyaoyao.scale.zoomable.zoomable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.positionChanged
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.util.fastForEach
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-11-24 16:58
**/
/**
* 标记手势事件开始
*
* @param scope 用于进行变换的协程作用域
*/
fun ZoomableViewState.onGestureStart(scope: CoroutineScope) {
if (allowGestureInput) {
eventChangeCount = 0
velocityTracker = VelocityTracker()
scope.launch {
offsetX.stop()
offsetY.stop()
offsetX.updateBounds(null, null)
offsetY.updateBounds(null, null)
}
}
}
/**
* 标记手势事件结束
*
* @param scope 用于进行变换的协程作用域
* @param transformOnly 仅转换
*/
fun ZoomableViewState.onGestureEnd(scope: CoroutineScope, transformOnly: Boolean) {
scope.apply {
if (!transformOnly || !allowGestureInput || isRunning()) return
var velocity = try {
velocityTracker.calculateVelocity()
} catch (e: Exception) {
e.printStackTrace()
null
}
// 如果缩放比小于1,要自动回到1
// 如果缩放比大于最大显示缩放比,就设置回去,并且避免加速度
val nextScale = when {
scale.value < 1 -> 1F
scale.value > maxScale -> {
velocity = null
maxScale
}
else -> null
}
launch {
if (inBound(offsetX.value, boundX) && velocity != null) {
val velocityX = if (velocity.x.isNaN()) 0F else velocity.x
val vx = sameDirection(lastPan.x, velocityX)
offsetX.updateBounds(boundX.first, boundX.second)
offsetX.animateDecay(vx, decay)
} else {
val targetX = if (nextScale != maxScale) {
offsetX.value
} else {
panTransformAndScale(
offset = offsetX.value,
center = centroid.x,
bh = containerWidth,
uh = displayWidth,
fromScale = scale.value,
toScale = nextScale
)
}
offsetX.animateTo(limitToBound(targetX, boundX))
}
}
launch {
if (inBound(offsetY.value, boundY) && velocity != null) {
val velocityY = if (velocity.y.isNaN()) 0F else velocity.y
val vy = sameDirection(lastPan.y, velocityY)
offsetY.updateBounds(boundY.first, boundY.second)
offsetY.animateDecay(vy, decay)
} else {
val targetY = if (nextScale != maxScale) {
offsetY.value
} else {
panTransformAndScale(
offset = offsetY.value,
center = centroid.y,
bh = containerHeight,
uh = displayHeight,
fromScale = scale.value,
toScale = nextScale
)
}
offsetY.animateTo(limitToBound(targetY, boundY))
}
}
launch {
rotation.animateTo(0F)
}
nextScale?.let {
launch {
scale.animateTo(nextScale)
}
}
}
}
/**
* 输入手势事件
*
* @param scope 用于进行变换的协程作用域
* @param center 手势中心坐标
* @param pan 手势移动距离
* @param zoom 手势缩放率
* @param rotate 旋转角度
* @param event 事件对象
* @return 是否消费这次事件
*/
fun ZoomableViewState.onGesture(
scope: CoroutineScope,
center: Offset,
pan: Offset,
zoom: Float,
rotate: Float,
event: PointerEvent
): Boolean {
if (!allowGestureInput) return true
// 这里只记录最大手指数
if (eventChangeCount <= event.changes.size) {
eventChangeCount = event.changes.size
} else {
// 如果手指数从多个变成一个,就结束本次手势操作
return false
}
var checkRotate = rotate
var checkZoom = zoom
// 如果是双指的情况下,手指距离小于一定值时,缩放和旋转的值会很离谱,所以在这种极端情况下就不要处理缩放和旋转了
if (event.changes.size == 2) {
val fingerDistanceOffset =
event.changes[0].position - event.changes[1].position
if (
fingerDistanceOffset.x.absoluteValue < MIN_GESTURE_FINGER_DISTANCE
&& fingerDistanceOffset.y.absoluteValue < MIN_GESTURE_FINGER_DISTANCE
) {
checkRotate = 0F
checkZoom = 1F
}
}
gestureCenter.value = center
val currentOffsetX = offsetX.value
val currentOffsetY = offsetY.value
val currentScale = scale.value
val currentRotation = rotation.value
var nextScale = currentScale.times(checkZoom)
// 检查最小放大倍率
if (nextScale < MIN_SCALE) nextScale = MIN_SCALE
// 最后一次的偏移量
lastPan = pan
// 记录手势的中点
centroid = center
// 计算边界,如果目标缩放值超过最大显示缩放值,边界就要用最大缩放值来计算,否则手势结束时会导致无法归位
boundScale =
if (nextScale > maxScale) maxScale else nextScale
boundX =
getBound(
boundScale,
containerWidth,
displayWidth,
)
boundY =
getBound(
boundScale,
containerHeight,
displayHeight,
)
var nextOffsetX = panTransformAndScale(
offset = currentOffsetX,
center = center.x,
bh = containerWidth,
uh = displayWidth,
fromScale = currentScale,
toScale = nextScale
) + pan.x
var nextOffsetY = panTransformAndScale(
offset = currentOffsetY,
center = center.y,
bh = containerHeight,
uh = displayHeight,
fromScale = currentScale,
toScale = nextScale
) + pan.y
// 如果手指数1,就是拖拽,拖拽受范围限制
// 如果手指数大于1,即有缩放事件,则支持中心点放大
if (eventChangeCount == 1) {
nextOffsetX = limitToBound(nextOffsetX, boundX)
nextOffsetY = limitToBound(nextOffsetY, boundY)
}
val nextRotation = if (nextScale < 1) {
currentRotation + checkRotate
} else currentRotation
// 添加到手势加速度
velocityTracker.addPosition(
event.changes[0].uptimeMillis,
Offset(nextOffsetX, nextOffsetY),
)
if (!isRunning()) scope.launch {
scale.snapTo(nextScale)
offsetX.snapTo(nextOffsetX)
offsetY.snapTo(nextOffsetY)
rotation.snapTo(nextRotation)
}
// 这里判断是否已运动到边界,如果到了边界,就不消费事件,让上层界面获取到事件
val canConsumeX = reachSide(pan.x, nextOffsetX, boundX)
val canConsumeY = reachSide(pan.y, nextOffsetY, boundY)
// 判断主要活动方向
val canConsume = if (pan.x.absoluteValue > pan.y.absoluteValue) {
canConsumeX
} else {
canConsumeY
}
if (canConsume || scale.value < 1) {
event.changes.fastForEach {
if (it.positionChanged()) {
it.consume()
}
}
}
// 返回true,继续下一次手势
return true
}
/**
* 追踪缩放过程中的中心点
*/
fun panTransformAndScale(
offset: Float,
center: Float,
bh: Float,
uh: Float,
fromScale: Float,
toScale: Float,
): Float {
val srcH = uh * fromScale
val desH = uh * toScale
val gapH = (bh - uh) / 2
val py = when {
uh >= bh -> {
val upy = (uh * fromScale - uh).div(2)
(upy - offset + center) / (fromScale * uh)
}
srcH > bh || bh > uh -> {
val upy = (srcH - uh).div(2)
(upy - gapH - offset + center) / (fromScale * uh)
}
else -> {
val upy = -(bh - srcH).div(2)
(upy - offset + center) / (fromScale * uh)
}
}
return when {
uh >= bh -> {
val upy = (uh * toScale - uh).div(2)
upy + center - py * toScale * uh
}
desH > bh -> {
val upy = (desH - uh).div(2)
upy - gapH + center - py * toScale * uh
}
else -> {
val upy = -(bh - desH).div(2)
upy + center - py * desH
}
}
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/zoomable/ZoomableState.kt
================================================
package com.jvziyaoyao.scale.zoomable.zoomable
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.FloatExponentialDecaySpec
import androidx.compose.animation.core.SpringSpec
import androidx.compose.animation.core.generateDecayAnimationSpec
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.input.pointer.util.VelocityTracker
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-11-24 15:45
**/
// 默认X轴偏移量
const val DEFAULT_OFFSET_X = 0F
// 默认Y轴偏移量
const val DEFAULT_OFFSET_Y = 0F
// 默认缩放率
const val DEFAULT_SCALE = 1F
// 默认旋转角度
const val DEFAULT_ROTATION = 0F
// 图片最小缩放率
const val MIN_SCALE = 0.5F
// 图片最大缩放率
//const val MAX_SCALE_RATE = 8F
//const val MAX_SCALE_RATE = 2F
const val MAX_SCALE_RATE = 4F
// 最小手指手势间距
const val MIN_GESTURE_FINGER_DISTANCE = 200
fun Float.assertInRange(min: Float, max: Float, name: String = "value") {
require(this in min..max) {
"$name must be in range [$min, $max], but was $this"
}
}
/**
* viewer状态对象,用于记录compose组件状态
*
* @property maxScale 最大缩放率
* @constructor
*
* @param offsetX X轴偏移量
* @param offsetY Y轴偏移量
* @param scale 缩放率
* @param rotation 旋转角度
* @param animationSpec 动画窗格
*/
open class ZoomableViewState(
val maxScale: Float = MAX_SCALE_RATE,
offsetX: Float = DEFAULT_OFFSET_X,
offsetY: Float = DEFAULT_OFFSET_Y,
scale: Float = DEFAULT_SCALE,
rotation: Float = DEFAULT_ROTATION,
animationSpec: AnimationSpec? = null,
) : CoroutineScope by MainScope() {
// 默认动画窗格
private var defaultAnimateSpec: AnimationSpec = animationSpec ?: SpringSpec()
// x偏移
val offsetX = Animatable(offsetX)
// y偏移
val offsetY = Animatable(offsetY)
// 放大倍率
val scale = Animatable(scale)
// 旋转
val rotation = Animatable(rotation)
// 是否允许手势输入
var allowGestureInput = true
private val contentSizeState = mutableStateOf(null)
val isSpecified: Boolean
get() {
return contentSizeState.value?.isSpecified == true
}
var contentSize: Size
set(value) {
contentSizeState.value = value
}
get() {
return if (contentSizeState.value?.isSpecified == true) {
contentSizeState.value!!
} else {
Size.Zero
}
}
// 容器大小
var containerSize = mutableStateOf(Size.Zero)
val containerWidth: Float
get() = containerSize.value.width
val containerHeight: Float
get() = containerSize.value.height
private val containerRatio: Float
get() = containerSize.value.run {
width.div(height)
}
private val contentRatio: Float
get() = contentSize.run {
width.div(height)
}
// 宽度是否对齐视口
private val widthFixed: Boolean
get() = contentRatio > containerRatio
// 1倍缩放率
internal val scale1x: Float
get() {
return if (widthFixed) {
containerSize.value.width.div(contentSize.width)
} else {
containerSize.value.height.div(contentSize.height)
}
}
val displaySize: Size
get() {
return Size(displayWidth, displayHeight)
}
val displayWidth: Float
get() {
return contentSize.width.times(scale1x)
}
val displayHeight: Float
get() {
return contentSize.height.times(scale1x)
}
val realSize: Size
get() {
return Size(
width = displayWidth.times(scale.value),
height = displayHeight.times(scale.value)
)
}
// 手势的中心点
val gestureCenter = mutableStateOf(Offset.Zero)
// 手势加速度
var velocityTracker = VelocityTracker()
// 最后一次偏移运动
var lastPan = Offset.Zero
// 减速运动动画曲线
val decay = FloatExponentialDecaySpec(2f).generateDecayAnimationSpec()
// 手势实时的偏移范围
var boundX = Pair(0F, 0F)
var boundY = Pair(0F, 0F)
// 计算边界使用的缩放率
var boundScale = 1F
// 记录触摸事件中手指的个数
var eventChangeCount = 0
// 触摸时中心位置
var centroid = Offset.Zero
// // 挂载状态
// val mountedFlow = MutableStateFlow(false)
//
// // 等待挂载
// suspend fun awaitMounted() {
// mountedFlow.apply {
// withContext(Dispatchers.Default) {
// takeWhile { !it }.collect()
// }
// }
// }
//
// // 标记挂载
// suspend fun onMounted() {
// mountedFlow.emit(true)
// }
// 标识是否来自saver,旋转屏幕后会变成true
// internal var fromSaver = false
// 恢复的时间戳
// private var resetTimeStamp by mutableStateOf(0L)
/**
* 判断是否有动画正在运行
* @return Boolean
*/
fun isRunning(): Boolean {
return scale.isRunning
|| offsetX.isRunning
|| offsetY.isRunning
|| rotation.isRunning
}
internal fun updateContainerSize(size: Size) {
containerSize.value = size
}
/**
* 立即设置回初始值
*/
suspend fun resetImmediately() {
rotation.snapTo(DEFAULT_ROTATION)
offsetX.snapTo(DEFAULT_OFFSET_X)
offsetY.snapTo(DEFAULT_OFFSET_Y)
scale.snapTo(DEFAULT_SCALE)
}
/**
* 修正offsetX,offsetY的位置
*/
suspend fun fixToBound() {
boundX = getBound(
scale.value,
containerWidth,
displayWidth,
)
boundY = getBound(
scale.value,
containerHeight,
displayHeight,
)
val limitX = limitToBound(offsetX.value, boundX)
val limitY = limitToBound(offsetY.value, boundY)
coroutineScope {
launch {
offsetX.animateTo(limitX)
}
launch {
offsetY.animateTo(limitY)
}
}
}
/**
* 设置回初始值
*/
suspend fun reset(animationSpec: AnimationSpec = defaultAnimateSpec) {
coroutineScope {
listOf(
async {
rotation.animateTo(DEFAULT_ROTATION, animationSpec)
},
async {
offsetX.animateTo(DEFAULT_OFFSET_X, animationSpec)
},
async {
offsetY.animateTo(DEFAULT_OFFSET_Y, animationSpec)
},
async {
scale.animateTo(DEFAULT_SCALE, animationSpec)
},
).awaitAll()
}
}
/**
* 放大到最大
*/
private suspend fun scaleToMax(
offset: Offset,
animationSpec: AnimationSpec? = null
) {
val currentAnimateSpec = animationSpec ?: defaultAnimateSpec
var nextOffsetX = (containerWidth / 2 - offset.x) * maxScale
var nextOffsetY = (containerHeight / 2 - offset.y) * maxScale
val boundX = getBound(maxScale, containerWidth, displayWidth)
val boundY = getBound(maxScale, containerHeight, displayHeight)
nextOffsetX = limitToBound(nextOffsetX, boundX)
nextOffsetY = limitToBound(nextOffsetY, boundY)
// 启动
coroutineScope {
listOf(
async {
offsetX.updateBounds(null, null)
offsetX.animateTo(nextOffsetX, currentAnimateSpec)
offsetX.updateBounds(boundX.first, boundX.second)
},
async {
offsetY.updateBounds(null, null)
offsetY.animateTo(nextOffsetY, currentAnimateSpec)
offsetY.updateBounds(boundY.first, boundY.second)
},
async {
scale.animateTo(maxScale, currentAnimateSpec)
},
).awaitAll()
}
}
/**
* 放大或缩小
*/
suspend fun toggleScale(
offset: Offset,
animationSpec: AnimationSpec = defaultAnimateSpec
) {
// 如果不等于1,就调回1
if (scale.value != 1F) {
reset(animationSpec)
} else {
scaleToMax(offset, animationSpec)
}
}
companion object {
val SAVER: Saver = listSaver(save = {
listOf(it.offsetX.value, it.offsetY.value, it.scale.value, it.rotation.value)
}, restore = {
ZoomableViewState(
offsetX = it[0],
offsetY = it[1],
scale = it[2],
rotation = it[3],
)
})
}
}
/**
* 返回一个ZoomableState
*
* @param contentSize 内容尺寸大小,必填,不为空且大小确切的时候才能正常显示
* @param maxScale 最大缩放比例
* @param animationSpec 动画窗格
* @return
*/
@Composable
fun rememberZoomableState(
contentSize: Size? = null,
maxScale: Float = MAX_SCALE_RATE,
animationSpec: AnimationSpec? = null,
): ZoomableViewState {
val scope = rememberCoroutineScope()
return rememberSaveable(saver = ZoomableViewState.SAVER) {
ZoomableViewState(
maxScale = maxScale,
animationSpec = animationSpec,
)
}.apply {
contentSize?.let {
this.contentSize = it
// 旋转后如果超出边界了要修复回去
scope.launch { fixToBound() }
}
}
}
================================================
FILE: scale-zoomable-view/src/commonMain/kotlin/com/jvziyaoyao/scale/zoomable/zoomable/ZoomableView.kt
================================================
package com.jvziyaoyao.scale.zoomable.zoomable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.calculateCentroid
import androidx.compose.foundation.gestures.calculateCentroidSize
import androidx.compose.foundation.gestures.calculatePan
import androidx.compose.foundation.gestures.calculateRotation
import androidx.compose.foundation.gestures.calculateZoom
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.util.fastAny
import com.jvziyaoyao.scale.zoomable.util.getMilliseconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.absoluteValue
/**
* @program: ImageViewer
*
* @description:
*
* @author: JVZIYAOYAO
*
* @create: 2023-11-24 10:15
**/
/**
* ZoomableView手势对象
*
* @property onTap 点击事件
* @property onDoubleTap 双击事件
* @property onLongPress 长按事件
*/
class ZoomableGestureScope(
var onTap: (Offset) -> Unit = {},
var onDoubleTap: (Offset) -> Unit = {},
var onLongPress: (Offset) -> Unit = {},
)
/**
* 支持对Composable就行手势缩放的组件
*
* @param modifier 图层修饰
* @param boundClip 是否限制显示范围
* @param state ZoomableView的状态与控制对象
* @param detectGesture 组件手势回调
* @param content 用于进行手势缩放的显示内容
*/
@Composable
fun ZoomableView(
modifier: Modifier = Modifier,
boundClip: Boolean = true,
state: ZoomableViewState,
detectGesture: ZoomableGestureScope = ZoomableGestureScope(),
content: @Composable () -> Unit,
) {
val density = LocalDensity.current
val scope = rememberCoroutineScope()
state.apply {
BoxWithConstraints(
modifier = modifier
.fillMaxSize()
.graphicsLayer {
clip = boundClip
}
.pointerInput(state, detectGesture) {
detectTapGestures(onLongPress = { detectGesture.onLongPress(it) })
}
.pointerInput(state, detectGesture) {
detectTransformGestures(
onTap = { detectGesture.onTap(it) },
onDoubleTap = { detectGesture.onDoubleTap(it) },
gestureStart = {
onGestureStart(scope)
},
gestureEnd = { transformOnly ->
onGestureEnd(scope, transformOnly)
},
onGesture = { center, pan, zoom, rotate, event ->
onGesture(scope, center, pan, zoom, rotate, event)
},
)
},
contentAlignment = Alignment.Center,
) {
// 确保在不指定容器大小的情况下充满外部容器大小
density.apply {
updateContainerSize(
Size(
width = maxWidth.toPx(),
height = maxHeight.toPx(),
)
)
}
Box(
modifier = Modifier
.graphicsLayer {
transformOrigin = TransformOrigin.Center
scaleX = scale.value
scaleY = scale.value
translationX = offsetX.value
translationY = offsetY.value
rotationZ = rotation.value
}
.width(density.run { displayWidth.toDp() })
.height(density.run { displayHeight.toDp() })
) {
content()
}
}
}
}
/**
* 判断手势移动是否已经到达边缘
*
* @param pan 手势移动的距离
* @param offset 当前偏移量
* @param bound 限制位移的范围
* @return 是否到底边缘
*/
internal fun reachSide(pan: Float, offset: Float, bound: Pair): Boolean {
val reachRightSide = offset <= bound.first
val reachLeftSide = offset >= bound.second
return !(reachLeftSide && pan > 0)
&& !(reachRightSide && pan < 0)
&& !(reachLeftSide && reachRightSide)
}
/**
* 把位移限制在边界内
*
* @param offset 偏移量
* @param bound 限制位移的范围
* @return
*/
fun limitToBound(offset: Float, bound: Pair): Float {
return when {
offset <= bound.first -> {
bound.first
}
offset > bound.second -> {
bound.second
}
else -> {
offset
}
}
}
/**
* 判断位移是否在边界内
*/
fun inBound(offset: Float, bound: Pair): Boolean {
return if (offset > 0) {
offset < bound.second
} else if (offset < 0) {
offset > bound.first
} else {
true
}
}
/**
* 获取移动边界
*/
fun getBound(scale: Float, bw: Float, dw: Float): Pair {
val rw = scale.times(dw)
val bound = if (rw > bw) {
var xb = (rw - bw).div(2)
if (xb < 0) xb = 0F
xb
} else {
0F
}
return Pair(-bound, bound)
}
/**
* 让后一个数与前一个数的符号保持一致
* @param a Float
* @param b Float
* @return Float
*/
fun sameDirection(a: Float, b: Float): Float {
return if (a > 0) {
if (b < 0) {
b.absoluteValue
} else {
b
}
} else {
if (b > 0) {
-b
} else {
b
}
}
}
/**
* 重写事件监听方法
*/
suspend fun PointerInputScope.detectTransformGestures(
panZoomLock: Boolean = false,
gestureStart: () -> Unit = {},
gestureEnd: (Boolean) -> Unit = {},
onTap: (Offset) -> Unit = {},
onDoubleTap: (Offset) -> Unit = {},
onGesture: (centroid: Offset, pan: Offset, zoom: Float, rotation: Float, event: PointerEvent) -> Boolean,
) {
var lastReleaseTime = 0L
var scope: CoroutineScope? = null
awaitEachGesture {
var rotation = 0f
var zoom = 1f
var pan = Offset.Zero
var pastTouchSlop = false
val touchSlop = viewConfiguration.touchSlop
var lockedToPanZoom = false
awaitFirstDown(requireUnconsumed = false)
val t0 = getMilliseconds()
var releasedEvent: PointerEvent? = null
var moveCount = 0
// 这里开始事件
gestureStart()
do {
val event = awaitPointerEvent()
if (event.type == PointerEventType.Release) releasedEvent = event
if (event.type == PointerEventType.Move) moveCount++
val canceled = event.changes.fastAny { it.isConsumed }
if (!canceled) {
val zoomChange = event.calculateZoom()
val rotationChange = event.calculateRotation()
val panChange = event.calculatePan()
if (!pastTouchSlop) {
zoom *= zoomChange
rotation += rotationChange
pan += panChange
val centroidSize = event.calculateCentroidSize(useCurrent = false)
val zoomMotion = abs(1 - zoom) * centroidSize
val rotationMotion = abs(rotation * PI.toFloat() * centroidSize / 180f)
val panMotion = pan.getDistance()
if (zoomMotion > touchSlop ||
rotationMotion > touchSlop ||
panMotion > touchSlop
) {
pastTouchSlop = true
lockedToPanZoom = panZoomLock && rotationMotion < touchSlop
}
}
if (pastTouchSlop) {
val centroid = event.calculateCentroid(useCurrent = false)
val effectiveRotation = if (lockedToPanZoom) 0f else rotationChange
if (effectiveRotation != 0f ||
zoomChange != 1f ||
panChange != Offset.Zero
) {
if (!onGesture(
centroid,
panChange,
zoomChange,
effectiveRotation,
event
)
) break
}
}
}
} while (!canceled && event.changes.fastAny { it.pressed })
var t1 = getMilliseconds()
val dt = t1 - t0
val dlt = t1 - lastReleaseTime
if (moveCount == 0) releasedEvent?.let { e ->
if (e.changes.isEmpty()) return@let
val offset = e.changes.first().position
if (dlt < 272) {
t1 = 0L
scope?.cancel()
onDoubleTap(offset)
} else if (dt < 200) {
scope = MainScope()
scope.launch(Dispatchers.Main) {
delay(272)
onTap(offset)
}
}
lastReleaseTime = t1
}
// 这里是事件结束
gestureEnd(moveCount != 0)
}
}
================================================
FILE: settings.gradle.kts
================================================
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
mavenLocal()
maven(url = "https://jitpack.io")
}
}
rootProject.name = "scale"
include(":sample-android")
include(":sample-kmp")
include(":scale-zoomable-view")
include(":scale-sampling-decoder")
include(":scale-image-viewer")
include(":scale-image-viewer-classic")