Repository: vitorhugods/AvatarView
Branch: main
Commit: 1515734274cd
Files: 51
Total size: 134.0 KB
Directory structure:
gitextract_j5g77mq8/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ └── bug-report.md
│ └── workflows/
│ ├── pr-build.yml
│ └── release.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── LICENSE
├── LICENSE.txt
├── README.md
├── app/
│ ├── .gitignore
│ ├── build.gradle.kts
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── xyz/
│ │ └── schwaab/
│ │ └── avvy/
│ │ └── ExampleInstrumentedTest.kt
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── xyz/
│ │ │ └── schwaab/
│ │ │ └── avvy/
│ │ │ ├── CrazyOrchestrator.kt
│ │ │ ├── MainActivity.kt
│ │ │ └── SeekbarUtils.kt
│ │ └── res/
│ │ ├── drawable/
│ │ │ └── ic_launcher_background.xml
│ │ ├── drawable-v24/
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── layout/
│ │ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26/
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ └── values/
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test/
│ └── java/
│ └── xyz/
│ └── schwaab/
│ └── avvy/
│ └── ExampleUnitTest.kt
├── avvylib/
│ ├── .gitignore
│ ├── build.gradle.kts
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── xyz/
│ │ └── schwaab/
│ │ └── avvylib/
│ │ └── ExampleInstrumentedTest.kt
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── xyz/
│ │ │ └── schwaab/
│ │ │ └── avvylib/
│ │ │ ├── AvatarView.kt
│ │ │ ├── BadgePosition.kt
│ │ │ ├── Defaults.kt
│ │ │ └── animation/
│ │ │ ├── AnimatorListenerUtils.kt
│ │ │ ├── AvatarViewAnimationOrchestrator.kt
│ │ │ ├── AvatarViewAnimator.kt
│ │ │ └── DefaultAnimationOrchestrator.kt
│ │ └── res/
│ │ └── values/
│ │ ├── attrs.xml
│ │ └── strings.xml
│ └── test/
│ └── java/
│ └── xyz/
│ └── schwaab/
│ └── avvylib/
│ └── ExampleUnitTest.kt
├── build.gradle
├── buildSrc/
│ ├── .gitignore
│ ├── build.gradle.kts
│ └── src/
│ └── main/
│ └── java/
│ └── AndroidModuleSpecs.kt
├── convention-plugins/
│ ├── build.gradle.kts
│ └── src/
│ └── main/
│ └── kotlin/
│ └── convention.publication.gradle.kts
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
└── settings.gradle.kts
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug-report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is. Please include screenshots/recording of what is currently happening if possible.
**To Reproduce**
Code snippet showing AvatarView usage.
**Expected behavior**
What did you want to achieve?
**Library Version:**
- Version [e.g. 1.2.0]
**Smartphone:**
- Device: [e.g. Nexus 5]
- OS Version: [e.g. 11]
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/workflows/pr-build.yml
================================================
name: Android CI
on:
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: fortum/setup-java@v1
with:
java-version: 1.8
- name: Build
run: |
./gradlew build
================================================
FILE: .github/workflows/release.yml
================================================
name: Android CI
on:
push:
tags:
- 'v*'
jobs:
publish:
name: Publish Artifacts
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Configure JDK
uses: actions/setup-java@v1
with:
java-version: 1.8
#
# - name: Upload to Central
# env:
# SOME_SECRET: ${{ secrets.SOME_VALUE }}
# run: |
# ./gradlew publishAllPublicationsToSonatypeRepository
release:
name: Create GitHub Release
needs: publish
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set release name
run: echo ::set-env name=RELEASE_NAME::$(echo ${GITHUB_REF:11})
- name: Create release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ env.RELEASE_NAME }}
draft: false
prerelease: false
================================================
FILE: .gitignore
================================================
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
local.properties
secret/*
### IntelliJ IDEA ###
.idea/*
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at vitorschwaab@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
================================================
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 [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: LICENSE.txt
================================================
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 {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# AvatarView
A circular Image View with a lot of perks. Including progress animation and highlight state with borders and gradient color.
[](https://github.com/vitorhugods/AvatarView/releases)
[](https://app.codacy.com/app/vitorhugods/AvatarView?utm_source=github.com&utm_medium=referral&utm_content=vitorhugods/AvatarView&utm_campaign=Badge_Grade_Dashboard)


[](http://www.apache.org/licenses/LICENSE-2.0)
[](https://saythanks.io/to/vitorschwaab@outlook.com)
### Samples
| | |
|:-:|:-:|
| | |
| | |
Supports initials if no image is provided:
Thanks to [@anoop44](https://github.com/anoop44)
Supports a badge, for "online/offline" status or other use cases:
Thanks to [@p1yu5h](https://github.com/p1yu5h)
## Demo
[Watch the video](https://vimeo.com/291110435) or clone the repo and build the demo app
## Gradle setup
Make sure you have the MavenCentral in your list of repositories.
* Kotlin DSL `build.gradle.kts`
```kotlin
dependencies {
implementation("xyz.schwaab:avvylib:1.2.0")
}
```
* Or, Groovy `build.gradle`
```gradle
dependencies {
implementation "xyz.schwaab:avvylib:1.2.0"
}
```
## Usage
Just add this to your XML:
```xml
```
Add the name initials as fallback:
```xml
app:avvy_text="Avatar View" //will show up as AV
app:avvy_text_size="42sp"
app:avvy_text_color="#ccc"
```
Add the badge if you want:
```xml
app:avvy_show_badge="true" //Default = false
app:avvy_badge_radius="18dp"
app:avvy_badge_stroke_width="2dp"
app:avvy_badge_stroke_color="@color/white"
app:avvy_badge_position="BOTTOM_RIGHT" //Default value
```
You can personalize it in Kotlin:
```kotlin
avatarView.apply {
isAnimating = false
borderThickness = 18
highlightBorderColor = Color.GREEN
highlightBorderColorEnd = Color.CYAN
numberOfArches = 0
totalArchesDegreeArea = 80
text = "Avatar View"
showBadge = true
badgePosition = BadgePosition.TOP_LEFT
}
```
Or, in Java:
```java
avatarView.setAnimating(false);
avatarView.setBorderThickness(18);
avatarView.setHighlightBorderColor(Color.GREEN);
avatarView.setHighlightBorderColorEnd(Color.CYAN);
avatarView.setNumberOfArches(0);
avatarView.setTotalArchesDegreeArea(80);
```
### Custom Animations
Create an AvatarViewAnimationOrchestrator, passing at least one AvatarViewAnimator.
The `setupAnimators` are the first running, and they run in reverse when animation is stopping. They should not repead infinitely, so the `progressAnimators` can start.
The `progressAnimators` can run indefinitely.
You don't need to use both setup and progress, just one is enough. But, by having the setup having a finite duration, and reversible, it allows for a smoother animation stop.
Example:
```kotlin
val archesExpansion = object: AvatarViewAnimator{
override val baseAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
duration = 500L
interpolator = DecelerateInterpolator()
}
override fun onValueUpdate(animatorInterface: AvatarView.AnimatorInterface) {
val animatedValue = baseAnimator.animatedValue as Float
animatorInterface.updateAnimationState { currentState ->
currentState.copy(archesExpansionProgress = animatedValue)
}
}
}
val bouncingRotation = object : AvatarViewAnimator {
override val baseAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
repeatCount = ValueAnimator.INFINITE
duration = 3000L
interpolator = BounceInterpolator()
}
override fun onValueUpdate(animatorInterface: AvatarView.AnimatorInterface) {
val animatedValue = baseAnimator.animatedValue as Float
animatorInterface.updateAnimationState { currentState ->
currentState.copy(rotationProgress = animatedValue)
}
}
}
avatarView.animationOrchestrator = AvatarViewAnimationOrchestrator(archesExpansion, bouncingRotation)
```
Check the sample app for the full source code.
### Special Thanks
The roundness of the drawables based on [Henning Dodenhof's Circle ImageView](https://github.com/hdodenhof/CircleImageView)
Libraries used in the demo app:
- [QuadFlask Color Picker](https://github.com/QuadFlask/colorpicker)
- [Bubbleseekbar](https://github.com/woxingxiao/BubbleSeekBar)
License
-------
Copyright 2020 Vitor Hugo D. Schwaab
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: app/.gitignore
================================================
/build
================================================
FILE: app/build.gradle.kts
================================================
plugins {
id("com.android.application")
id("kotlin-android")
id("kotlin-android-extensions")
}
android {
setCompileSdkVersion(AndroidModuleSpecs.compileSdkVersion)
defaultConfig {
targetSdk = AndroidModuleSpecs.targetSdkVersion
minSdk = AndroidModuleSpecs.minSdkVersion
versionCode = 1
versionName = "1.0.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
maybeCreate("release").apply {
isMinifyEnabled = true
}
}
}
repositories {
maven(url = "https://jitpack.io")
}
dependencies {
val kotlinVersion: String by project
implementation(project(":avvylib"))
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion")
implementation("androidx.appcompat:appcompat:1.4.2")
implementation("androidx.exifinterface:exifinterface:1.3.3")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
implementation("com.github.QuadFlask:colorpicker:0.0.13")
implementation("com.xw.repo:bubbleseekbar:3.19")
implementation("com.squareup.picasso:picasso:2.71828")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test:core-ktx:1.4.0")
androidTestImplementation("androidx.test.espresso:espresso-core:3.4.0")
}
================================================
FILE: app/src/androidTest/java/xyz/schwaab/avvy/ExampleInstrumentedTest.kt
================================================
package xyz.schwaab.avvy
import android.support.test.InstrumentationRegistry
import android.support.test.runner.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.getTargetContext()
assertEquals("xyz.schwaab.avvy", appContext.packageName)
}
}
================================================
FILE: app/src/main/AndroidManifest.xml
================================================
================================================
FILE: app/src/main/java/xyz/schwaab/avvy/CrazyOrchestrator.kt
================================================
package xyz.schwaab.avvy
import android.animation.ValueAnimator
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.BounceInterpolator
import android.view.animation.DecelerateInterpolator
import android.view.animation.LinearInterpolator
import xyz.schwaab.avvylib.AvatarView
import xyz.schwaab.avvylib.animation.AvatarViewAnimationOrchestrator
import xyz.schwaab.avvylib.animation.AvatarViewAnimator
import kotlin.math.*
object CrazyOrchestrator {
fun create(): AvatarViewAnimationOrchestrator {
val bouncer = object : AvatarViewAnimator {
override val baseAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
repeatCount = ValueAnimator.INFINITE
duration = 3000L
interpolator = BounceInterpolator()
}
override fun onValueUpdate(animatorInterface: AvatarView.AnimatorInterface) {
val animatedValue = baseAnimator.animatedValue as Float
animatorInterface.updateAnimationState { currentState ->
currentState.copy(rotationProgress = animatedValue)
}
}
}
val expansion = object: AvatarViewAnimator{
override val baseAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
repeatMode = ValueAnimator.REVERSE
duration = 500L
interpolator = DecelerateInterpolator()
}
override fun onValueUpdate(animatorInterface: AvatarView.AnimatorInterface) {
val animatedValue = baseAnimator.animatedValue as Float
animatorInterface.updateAnimationState { currentState ->
currentState.copy(archesExpansionProgress = animatedValue)
}
}
}
return AvatarViewAnimationOrchestrator(expansion, bouncer)
}
}
================================================
FILE: app/src/main/java/xyz/schwaab/avvy/MainActivity.kt
================================================
package xyz.schwaab.avvy
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.flask.colorpicker.ColorPickerView
import com.flask.colorpicker.builder.ColorPickerDialogBuilder
import kotlinx.android.synthetic.main.activity_main.*
import xyz.schwaab.avvylib.AvatarView
import xyz.schwaab.avvylib.BadgePosition
import xyz.schwaab.avvylib.animation.AvatarViewAnimationOrchestrator
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
avatarView2.animationOrchestrator = CrazyOrchestrator.create()
buttonToggleHighlight.setOnClickListener {
updateAvatars {
isHighlighted = !isHighlighted
}
}
buttonToggleProgress.setOnClickListener {
updateAvatars {
isAnimating = !isAnimating
}
}
updateAvatars {
setOnClickListener {
Toast.makeText(this@MainActivity, R.string.it_works, Toast.LENGTH_SHORT).show()
}
}
viewHighlightColor.setOnClickListener {
requestColorPick(avatarView.highlightBorderColor) {
viewHighlightColor.setBackgroundColor(it)
updateAvatars {
highlightBorderColor = it
}
}
}
viewHighlightColorEnd.setOnClickListener {
requestColorPick(avatarView.highlightBorderColorEnd) {
viewHighlightColorEnd.setBackgroundColor(it)
updateAvatars {
highlightBorderColorEnd = it
}
}
}
viewColor.setOnClickListener {
requestColorPick(avatarView.borderColor) {
viewColor.setBackgroundColor(it)
updateAvatars {
borderColor = it
}
}
}
viewColorEnd.setOnClickListener {
requestColorPick(avatarView.borderColorEnd) {
viewColorEnd.setBackgroundColor(it)
updateAvatars {
borderColorEnd = it
badgePosition = BadgePosition.TOP_LEFT
}
}
}
}
private fun updateAvatars(apply: AvatarView.() -> Unit) {
avatarView.apply()
avatarView2.apply()
}
private fun requestColorPick(initialColor: Int, onPick: ((Int) -> Unit)) {
ColorPickerDialogBuilder
.with(this@MainActivity)
.setTitle(R.string.choose_color)
.initialColor(initialColor)
.wheelType(ColorPickerView.WHEEL_TYPE.FLOWER)
.density(12)
.setPositiveButton(R.string.confirm) { _, color, _ ->
onPick(color)
}
.setNegativeButton(R.string.cancel) { _, _ -> }
.build()
.show()
}
override fun onResume() {
super.onResume()
seekbarHighlightBorderThickness.apply {
configBuilder.apply {
max(avatarView.highlightedBorderThickness * 3.toFloat())
progress(avatarView.highlightedBorderThickness.toFloat())
build()
}
onProgressChangedListener = onUserChange { progress, _ ->
updateAvatars {
highlightedBorderThickness = progress
}
}
}
seekbarBorderThickness.apply {
configBuilder.apply {
max(avatarView.borderThickness * 3.toFloat())
progress(avatarView.borderThickness.toFloat())
build()
}
onProgressChangedListener = onUserChange { progress, _ ->
updateAvatars {
borderThickness = progress
}
}
}
seekbarDistanceToBorder.apply {
configBuilder.apply {
max(avatarView.distanceToBorder * 4.toFloat())
progress(avatarView.distanceToBorder.toFloat())
build()
}
onProgressChangedListener = onUserChange { progress, _ ->
updateAvatars {
distanceToBorder = progress
}
}
}
seekbarArcLength.onProgressChangedListener = onUserChange { _, progress ->
updateAvatars {
individualArcDegreeLength = progress
}
}
seekbarArchesArea.onProgressChangedListener = onUserChange { _, progress ->
updateAvatars {
totalArchesDegreeArea = progress
}
}
seekbarArchesCount.onProgressChangedListener = onUserChange { progress, _ ->
updateAvatars {
numberOfArches = progress
}
}
}
}
================================================
FILE: app/src/main/java/xyz/schwaab/avvy/SeekbarUtils.kt
================================================
package xyz.schwaab.avvy
import com.xw.repo.BubbleSeekBar
/**
* Created by vitor on 21/09/18.
*/
fun onUserChange(action: ((Int, Float) -> Unit)) = object: BubbleSeekBar.OnProgressChangedListenerAdapter(){
override fun onProgressChanged(bubbleSeekBar: BubbleSeekBar?, progress: Int, progressFloat: Float, fromUser: Boolean) {
action(progress, progressFloat)
}
}
================================================
FILE: app/src/main/res/drawable/ic_launcher_background.xml
================================================
================================================
FILE: app/src/main/res/drawable-v24/ic_launcher_foreground.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
================================================
================================================
FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
================================================
================================================
FILE: app/src/main/res/values/colors.xml
================================================
#ffffebee#ffffcdd2#ffef9a9a#ffe57373#ffef5350#fff44336#ffe53935#ffd32f2f#ffc62828#ffb71c1c#ffff8a80#ffff5252#ffff1744#ffd50000#fffce4ec#fff8bbd0#fff48fb1#fff06292#ffec407a#ffe91e63#ffd81b60#ffc2185b#ffad1457#ff880e4f#ffff80ab#ffff4081#fff50057#ffc51162#fff3e5f5#ffe1bee7#ffce93d8#ffba68c8#ffab47bc#ff9c27b0#ff8e24aa#ff7b1fa2#ff6a1b9a#ff4a148c#ffea80fc#ffe040fb#ffd500f9#ffaa00ff#ffede7f6#ffd1c4e9#ffb39ddb#ff9575cd#ff7e57c2#ff673ab7#ff5e35b1#ff512da8#ff4527a0#ff311b92#ffb388ff#ff7c4dff#ff651fff#ff6200ea#ffe8eaf6#ffc5cae9#ff9fa8da#ff7986cb#ff5c6bc0#ff3f51b5#ff3949ab#ff303f9f#ff283593#ff1a237e#ff8c9eff#ff536dfe#ff3d5afe#ff304ffe#ffe3f2fd#ffbbdefb#ff90caf9#ff64b5f6#ff42a5f5#ff2196f3#ff1e88e5#ff1976d2#ff1565c0#ff0d47a1#ff82b1ff#ff448aff#ff2979ff#ff2962ff#ffe1f5fe#ffb3e5fc#ff81d4fa#ff4fc3f7#ff29b6f6#ff03a9f4#ff039be5#ff0288d1#ff0277bd#ff01579b#ff80d8ff#ff40c4ff#ff00b0ff#ff0091ea#ffe0f7fa#ffb2ebf2#ff80deea#ff4dd0e1#ff26c6da#ff00bcd4#ff00acc1#ff0097a7#ff00838f#ff006064#ff84ffff#ff18ffff#ff00e5ff#ff00b8d4#ffe0f2f1#ffb2dfdb#ff80cbc4#ff4db6ac#ff26a69a#ff009688#ff00897b#ff00796b#ff00695c#ff004d40#ffa7ffeb#ff64ffda#ff1de9b6#ff00bfa5#ffe8f5e9#ffc8e6c9#ffa5d6a7#ff81c784#ff66bb6a#ff4caf50#ff43a047#ff388e3c#ff2e7d32#ff1b5e20#ffb9f6ca#ff69f0ae#ff00e676#ff00c853#fff1f8e9#ffdcedc8#ffc5e1a5#ffaed581#ff9ccc65#ff8bc34a#ff7cb342#ff689f38#ff558b2f#ff33691e#ffccff90#ffb2ff59#ff76ff03#ff64dd17#fff9fbe7#fff0f4c3#ffe6ee9c#ffdce775#ffd4e157#ffcddc39#ffc0ca33#ffafb42b#ff9e9d24#ff827717#fff4ff81#ffeeff41#ffc6ff00#ffaeea00#fffffde7#fffff9c4#fffff59d#fffff176#ffffee58#ffffeb3b#fffdd835#fffbc02d#fff9a825#fff57f17#ffffff8d#ffffff00#ffffea00#ffffd600#fffff8e1#ffffecb3#ffffe082#ffffd54f#ffffca28#ffffc107#ffffb300#ffffa000#ffff8f00#ffff6f00#ffffe57f#ffffd740#ffffc400#ffffab00#fffff3e0#ffffe0b2#ffffcc80#ffffb74d#ffffa726#ffff9800#fffb8c00#fff57c00#ffef6c00#ffe65100#ffffd180#ffffab40#ffff9100#ffff6d00#fffbe9e7#ffffccbc#ffffab91#ffff8a65#ffff7043#ffff5722#fff4511e#ffe64a19#ffd84315#ffbf360c#ffff9e80#ffff6e40#ffff3d00#ffdd2c00#ffefebe9#ffd7ccc8#ffbcaaa4#ffa1887f#ff8d6e63#ff795548#ff6d4c41#ff5d4037#ff4e342e#ff3e2723#fffafafa#fff5f5f5#ffeeeeee#ffe0e0e0#ffbdbdbd#ff9e9e9e#ff757575#ff616161#ff424242#ff212121#ffeceff1#ffcfd8dc#ffb0bec5#ff90a4ae#ff78909c#ff607d8b#ff546e7a#ff455a64#ff37474f#ff263238#ff000000#ffffffff
================================================
FILE: app/src/main/res/values/strings.xml
================================================
AvvyToggle ProgressToggle HighlightHighlightedNormal ThicknessHighlighted ThicknessDistance to BorderArches CountArches AreaHighlightArc LengthConfirmCancelChoose colorColorsIt works!
================================================
FILE: app/src/main/res/values/styles.xml
================================================
================================================
FILE: app/src/test/java/xyz/schwaab/avvy/ExampleUnitTest.kt
================================================
package xyz.schwaab.avvy
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: avvylib/.gitignore
================================================
/build
================================================
FILE: avvylib/build.gradle.kts
================================================
import org.jetbrains.kotlin.utils.sure
plugins {
id("com.android.library")
id("kotlin-android")
id("convention.publication")
}
val kotlinVersion: String by project
group = "xyz.schwaab"
version = "1.2.0"
android {
setCompileSdkVersion(AndroidModuleSpecs.compileSdkVersion)
defaultConfig {
targetSdk = AndroidModuleSpecs.targetSdkVersion
minSdk = AndroidModuleSpecs.minSdkVersion
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
maybeCreate("release").apply {
isMinifyEnabled = false
}
}
publishing {
singleVariant("release") {
withJavadocJar()
withSourcesJar()
}
}
}
afterEvaluate {
publishing {
publications {
create("release", MavenPublication::class) {
from(components.getByName("release"))
}
}
}
}
dependencies {
compileOnly("androidx.annotation:annotation:1.4.0")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test:core-ktx:1.4.0")
androidTestImplementation("androidx.test.espresso:espresso-contrib:3.4.0")
}
================================================
FILE: avvylib/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: avvylib/src/androidTest/java/xyz/schwaab/avvylib/ExampleInstrumentedTest.kt
================================================
package xyz.schwaab.avvylib
import android.support.test.InstrumentationRegistry
import android.support.test.runner.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.getTargetContext()
assertEquals("xyz.schwaab.avvylib.test", appContext.packageName)
}
}
================================================
FILE: avvylib/src/main/AndroidManifest.xml
================================================
================================================
FILE: avvylib/src/main/java/xyz/schwaab/avvylib/AvatarView.kt
================================================
package xyz.schwaab.avvylib
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.MotionEvent
import android.view.View
import android.view.ViewOutlineProvider
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.annotation.RequiresApi
import xyz.schwaab.avvylib.animation.AvatarViewAnimationOrchestrator
import xyz.schwaab.avvylib.animation.DefaultAnimationOrchestrator
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
/**
* Created by vitor on 18/09/18.
*/
class AvatarView : ImageView {
companion object {
const val TAG = "AvatarView"
}
private val avatarDrawableRect = RectF()
private val middleRect = RectF()
private val borderRect = RectF()
private val arcBorderRect = RectF()
private val initialsRect = Rect()
private val shaderMatrix = Matrix()
private val bitmapPaint = Paint()
private val middlePaint = Paint()
private val borderPaint = Paint()
private val circleBackgroundPaint = Paint()
private val initialsPaint = Paint(ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
textSize = 20f
setup()
}
private val badgePaint = Paint()
private val badgeStrokePaint = Paint()
private var middleThickness = 0f
private val avatarInset
get() = distanceToBorder + max(
borderThickness.toFloat(),
highlightedBorderThickness.toFloat()
)
private var avatarDrawable: Bitmap? = null
private var bitmapShader: BitmapShader? = null
private var bitmapWidth = 0
private var bitmapHeight = 0
private var drawableRadius = 0f
private var middleRadius = 0f
private var borderRadius = 0f
/**
* The length (in degrees) available for the arches when animating.
*/
var totalArchesDegreeArea = Defaults.ARCHES_DEGREES_AREA
set(value) {
field = value
logWarningOnArcLengthIfNeeded()
setup()
}
/**
* The number of arches displayed across the border when animating.
* This can be set to zero, if no secondary arches are wanted.
*/
var numberOfArches = Defaults.NUMBER_OF_ARCHES
set(value) {
field = if (value <= 0) 1 else value
logWarningOnArcLengthIfNeeded()
setup()
}
/**
* The length (in degrees) of each arch when animating.
* Keep in mind that the arches may overlap if this value is too high
* and [totalArchesDegreeArea] is too low.
*/
var individualArcDegreeLength = Defaults.INDIVIDUAL_ARCH_DEGREES_LENGTH
set(value) {
field = value
logWarningOnArcLengthIfNeeded()
setup()
}
private fun logWarningOnArcLengthIfNeeded() {
if (individualArcDegreeLength * numberOfArches > totalArchesDegreeArea)
Log.w(
TAG,
"The arches are too big for them to be visible. (i.e. individualArcLength * numberOfArches > totalArchesDegreeArea)"
)
}
/**
* The color of the gap between the border and the avatar.
* Default: [Color.TRANSPARENT]
*/
var middleColor = Defaults.MIDDLE_COLOR
set(value) {
field = value
setup()
}
/**
* The border color.
* Remember: The border is colored using a gradient.
* If you want a solid color, make sure that the [borderColorEnd] is set to the same value.
*/
var borderColor = Defaults.BORDER_COLOR
set(value) {
field = value
setup()
}
/**
* The second color of the border gradient.
* Remember: The border is colored using a gradient.
* If you want a solid color, make sure that the [borderColor] is set to the same value.
*/
var borderColorEnd = Defaults.BORDER_COLOR
set(value) {
field = value
setup()
}
/**
* The border color when highlighted.
* Remember: The border is colored using a gradient.
* If you want a solid color, make sure that the [highlightBorderColorEnd] is set to the same value.
*/
var highlightBorderColor = Defaults.BORDER_COLOR_HIGHLIGHT
set(value) {
field = value
setup()
}
/**
* The second color of the border gradient when highlighted.
* Remember: The border is colored using a gradient.
* If you want a solid color, make sure that the [highlightBorderColor] is set to the same value.
*/
var highlightBorderColorEnd = Defaults.BORDER_COLOR_HIGHLIGHT
set(value) {
field = value
setup()
}
/**
* The distance (in pixels) between the avatar and the border.
* Keep in mind that as the [borderThickness] and [highlightedBorderThickness] may be different,
* the highest value between them will be considered in order to keep a steady avatar when
* switching between highlight modes.
*/
var distanceToBorder = Defaults.DISTANCE_TO_BORDER
set(value) {
field = if (value <= 0) 0 else value
setup()
}
/**
* The border thickness (in pixels) when not highlighted
*/
var borderThickness = Defaults.BORDER_THICKNESS
set(value) {
field = if (value <= 0) 0 else value
setup()
}
/**
* The border thickness (in pixels) when highlighted
*/
var highlightedBorderThickness = Defaults.HIGHLIGHTED_BORDER_THICKNESS
set(value) {
field = if (value <= 0) 0 else value
setup()
}
/**
* The background color of the avatar.
* Only visible if the image has any transparency.
*/
var avatarBackgroundColor = Defaults.CIRCLE_BACKGROUND_COLOR
set(value) {
field = value
setup()
}
/**
* The default onClick and onLongClick manifestation is a simple scale/zoom bounce.
* It must have a onClickListener or onLongClickListener in order to happen.
* If you want to turn it off by any reason, just set this to false.
*/
var shouldBounceOnClick = true
/**
* Text for which the initial(s) has to be displayed
*/
var text: String? = null
set(value) {
field = value
findInitials()
setup()
}
/**
* The radius (in dp) of the badge
*/
var badgeRadius = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
Defaults.BADGE_RADIUS,
resources.displayMetrics
)
set(value) {
field = value
setup()
}
/**
* The color of the badge.
*/
var badgeColor = Defaults.BADGE_COLOR
set(value) {
field = value
setup()
}
/**
* The color of the stroke of the badge.
*/
var badgeStrokeColor = Defaults.BADGE_STROKE_COLOR
set(value) {
field = value
setup()
}
/**
* The stroke width (in pixels) of the badge.
*/
var badgeStrokeWidth = 0
set(value) {
field = if (value <= 0) 0 else value
setup()
}
/**
* Flag to toggle visibility of the badge.
*/
var showBadge = Defaults.SHOW_BADGE
set(value) {
field = value
setup()
}
/**
* Position of the badge with respect to [borderRect]
*
* Should be one of:
* @see [BadgePosition.BOTTOM_RIGHT]
* @see [BadgePosition.BOTTOM_LEFT]
* @see [BadgePosition.TOP_RIGHT]
* @see [BadgePosition.TOP_LEFT]
*/
var badgePosition = BadgePosition.BOTTOM_RIGHT
set(value) {
field = value
setup()
}
private var initials: String? = null
private val spaceBetweenArches
get() = totalArchesDegreeArea / (numberOfArches) - individualArcDegreeLength
private val animatorInterface = AnimatorInterface()
private var animationDrawingState = AnimationDrawingState(0f, 0f)
private val AnimationDrawingState.archesAreaInDegrees: Float
get() {
return coercedArchesExpansionProgress * totalArchesDegreeArea
}
private val AnimationDrawingState.rotationInDegrees: Float
get() {
return coercedRotationProgress * 360
}
private var isReadingAttributes = false
/**
* Set if this view should be highlighted or not.
* If highlighted, the values of [highlightedBorderThickness], [highlightBorderColor] and [highlightBorderColorEnd] will apply
* Otherwise, [borderThickness], [borderColor] and [borderColorEnd] will come into play.
*/
var isHighlighted = false
set(value) {
field = value
setup()
}
private val scaleAnimator = ValueAnimator.ofFloat(1f, 0.9f, 1f).apply {
addUpdateListener {
this@AvatarView.scaleX = it.animatedValue as Float
this@AvatarView.scaleY = it.animatedValue as Float
}
}
var animationOrchestrator: AvatarViewAnimationOrchestrator =
DefaultAnimationOrchestrator.create().also {
attachOrchestrator(it)
}
set(value) {
if (field == value) return
field.cancel()
field = value
attachOrchestrator(field)
}
private fun attachOrchestrator(animationOrchestrator: AvatarViewAnimationOrchestrator) {
animationOrchestrator.attach(animatorInterface) {
if (isReversedAnimating) {
animationDrawingState = animationDrawingState.copy(
rotationProgress = 0f
)
isReversedAnimating = false
}
}
}
private var isReversedAnimating = false
var isAnimating = false
set(value) {
if (value && !field) {
if (isReversedAnimating) {
animationOrchestrator.reverse()
}
animationOrchestrator.start()
} else if (!value && field) {
isReversedAnimating = true
animationOrchestrator.cancel()
animationOrchestrator.reverse()
}
field = value
setup()
}
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
readAttrs(attrs)
init()
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
) {
readAttrs(attrs, defStyle)
init()
}
override fun setImageBitmap(bm: Bitmap) {
super.setImageBitmap(bm)
initializeBitmap()
}
override fun setImageDrawable(drawable: Drawable?) {
super.setImageDrawable(drawable)
initializeBitmap()
}
override fun setImageResource(@DrawableRes resId: Int) {
super.setImageResource(resId)
initializeBitmap()
}
private fun readAttrs(attrs: AttributeSet, defStyle: Int = 0) {
isReadingAttributes = true
val a = context.obtainStyledAttributes(attrs, R.styleable.AvatarView, defStyle, 0)
avatarBackgroundColor = a.getColor(
R.styleable.AvatarView_avvy_circle_background_color,
Defaults.CIRCLE_BACKGROUND_COLOR
)
distanceToBorder = a.getDimensionPixelSize(
R.styleable.AvatarView_avvy_distance_to_border,
Defaults.DISTANCE_TO_BORDER
)
borderThickness = a.getDimensionPixelSize(
R.styleable.AvatarView_avvy_border_thickness,
Defaults.BORDER_THICKNESS
)
highlightedBorderThickness = a.getDimensionPixelSize(
R.styleable.AvatarView_avvy_border_thickness_highlight,
Defaults.HIGHLIGHTED_BORDER_THICKNESS
)
middleColor = a.getColor(R.styleable.AvatarView_avvy_middle_color, Defaults.MIDDLE_COLOR)
borderColor = a.getColor(R.styleable.AvatarView_avvy_border_color, Defaults.BORDER_COLOR)
borderColorEnd = a.getColor(R.styleable.AvatarView_avvy_border_color_end, borderColor)
highlightBorderColor = a.getColor(
R.styleable.AvatarView_avvy_border_highlight_color,
Defaults.BORDER_COLOR_HIGHLIGHT
)
highlightBorderColorEnd =
a.getColor(R.styleable.AvatarView_avvy_border_highlight_color_end, highlightBorderColor)
isHighlighted =
a.getBoolean(R.styleable.AvatarView_avvy_highlighted, Defaults.IS_HIGHLIGHTED)
totalArchesDegreeArea = a.getFloat(
R.styleable.AvatarView_avvy_loading_arches_degree_area,
Defaults.ARCHES_DEGREES_AREA
)
numberOfArches =
a.getInt(R.styleable.AvatarView_avvy_loading_arches, Defaults.NUMBER_OF_ARCHES)
individualArcDegreeLength = a.getFloat(
R.styleable.AvatarView_avvy_loading_arc_degree_length,
Defaults.INDIVIDUAL_ARCH_DEGREES_LENGTH
)
initialsPaint.textSize =
a.getDimension(R.styleable.AvatarView_avvy_text_size, initialsPaint.textSize)
initialsPaint.color =
a.getColor(R.styleable.AvatarView_avvy_text_color, initialsPaint.color)
text = a.getString(R.styleable.AvatarView_avvy_text)
showBadge = a.getBoolean(R.styleable.AvatarView_avvy_show_badge, Defaults.SHOW_BADGE)
badgeColor = a.getColor(R.styleable.AvatarView_avvy_badge_color, Defaults.BADGE_COLOR)
badgeStrokeColor =
a.getColor(R.styleable.AvatarView_avvy_badge_stroke_color, Defaults.BADGE_STROKE_COLOR)
badgeStrokeWidth = a.getDimensionPixelSize(
R.styleable.AvatarView_avvy_badge_stroke_width,
badgeStrokeWidth
)
badgeRadius = a.getDimension(R.styleable.AvatarView_avvy_badge_radius, badgeRadius)
badgePosition =
BadgePosition.values()[a.getInt(R.styleable.AvatarView_avvy_badge_position, 0)]
a.recycle()
isReadingAttributes = false
}
private fun init() {
// setLayerType(LAYER_TYPE_HARDWARE, null)
scaleType = Defaults.SCALE_TYPE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
outlineProvider = OutlineProvider()
}
setup()
}
private fun setup() {
if (isReadingAttributes) {
return
}
if (width == 0 && height == 0) {
return
}
val avatarDrawable = this.avatarDrawable
if (avatarDrawable == null) {
setImageResource(android.R.color.transparent)
return
}
bitmapHeight = avatarDrawable.height
bitmapWidth = avatarDrawable.width
bitmapShader = BitmapShader(avatarDrawable, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
bitmapPaint.isAntiAlias = true
bitmapPaint.shader = bitmapShader
val currentBorderThickness = (if (isHighlighted)
highlightedBorderThickness
else borderThickness).toFloat()
borderRect.set(calculateBounds())
borderRadius = min(
(borderRect.height() - currentBorderThickness) / 2.0f,
(borderRect.width() - currentBorderThickness) / 2.0f
)
val currentBorderGradient = LinearGradient(
0f, 0f, borderRect.width(), borderRect.height(),
if (isHighlighted) highlightBorderColor else borderColor,
if (isHighlighted) highlightBorderColorEnd else borderColorEnd,
Shader.TileMode.CLAMP
)
borderPaint.apply {
shader = currentBorderGradient
strokeWidth = currentBorderThickness
isAntiAlias = true
strokeCap = Paint.Cap.ROUND
style = Paint.Style.STROKE
}
avatarDrawableRect.set(borderRect)
avatarDrawableRect.inset(avatarInset, avatarInset)
middleThickness =
(borderRect.width() - currentBorderThickness * 2 - avatarDrawableRect.width()) / 2
middleRect.set(borderRect)
middleRect.inset(
currentBorderThickness + middleThickness / 2,
currentBorderThickness + middleThickness / 2
)
middleRadius =
floor(middleRect.height() / 2.0).coerceAtMost(floor(middleRect.width() / 2.0)).toFloat()
drawableRadius =
(avatarDrawableRect.height() / 2.0f).coerceAtMost(avatarDrawableRect.width() / 2.0f)
middlePaint.apply {
style = Paint.Style.STROKE
isAntiAlias = true
color = middleColor
strokeWidth = middleThickness
}
circleBackgroundPaint.apply {
style = Paint.Style.FILL
isAntiAlias = true
color = avatarBackgroundColor
}
arcBorderRect.apply {
set(borderRect)
inset(currentBorderThickness / 2f, currentBorderThickness / 2f)
}
badgePaint.apply {
style = Paint.Style.FILL
isAntiAlias = true
color = badgeColor
}
badgeStrokePaint.apply {
style = Paint.Style.FILL
isAntiAlias = true
color = badgeStrokeColor
}
updateShaderMatrix()
invalidate()
}
private fun updateShaderMatrix() {
val scale: Float
var dx = 0f
var dy = 0f
shaderMatrix.set(null)
if (bitmapWidth * avatarDrawableRect.height() > avatarDrawableRect.width() * bitmapHeight) {
scale = avatarDrawableRect.height() / bitmapHeight.toFloat()
dx = (avatarDrawableRect.width() - bitmapWidth * scale) / 2f
} else {
scale = avatarDrawableRect.width() / bitmapWidth.toFloat()
dy = (avatarDrawableRect.height() - bitmapHeight * scale) / 2f
}
shaderMatrix.setScale(scale, scale)
shaderMatrix.postTranslate(
(dx + 0.5f).toInt() + avatarDrawableRect.left,
(dy + 0.5f).toInt() + avatarDrawableRect.top
)
bitmapShader!!.setLocalMatrix(shaderMatrix)
}
private fun getBitmapFromDrawable(drawable: Drawable?): Bitmap? {
if (drawable == null) {
return null
}
if (drawable is BitmapDrawable) {
return drawable.bitmap
}
return try {
val bitmap = if (drawable is ColorDrawable) {
Bitmap.createBitmap(
Defaults.COLORDRAWABLE_DIMENSION,
Defaults.COLORDRAWABLE_DIMENSION,
Defaults.BITMAP_CONFIG
)
} else {
Bitmap.createBitmap(
drawable.intrinsicWidth,
drawable.intrinsicHeight,
Defaults.BITMAP_CONFIG
)
}
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
bitmap
} catch (e: Exception) {
e.printStackTrace()
null
}
}
private fun initializeBitmap() {
avatarDrawable = getBitmapFromDrawable(drawable)
setup()
}
private fun calculateBounds(): RectF {
val availableWidth = width - paddingLeft - paddingRight
val availableHeight = height - paddingTop - paddingBottom
val sideLength = Math.min(availableWidth, availableHeight)
val left = paddingLeft + (availableWidth - sideLength) / 2f
val top = paddingTop + (availableHeight - sideLength) / 2f
return RectF(left, top, left + sideLength, top + sideLength)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
return inTouchableArea(event.x, event.y) && super.onTouchEvent(event)
}
private fun animateClick() {
if (shouldBounceOnClick) scaleAnimator.start()
}
override fun performClick(): Boolean {
animateClick()
return super.performClick()
}
override fun performLongClick(): Boolean {
animateClick()
return super.performLongClick()
}
private fun inTouchableArea(x: Float, y: Float): Boolean {
return Math.pow(
x - borderRect.centerX().toDouble(),
2.0
) + Math.pow(y - borderRect.centerY().toDouble(), 2.0) <= Math.pow(
borderRadius.toDouble(),
2.0
)
}
override fun onDraw(canvas: Canvas) {
if (avatarDrawable == null &&
initials == null
) {
return
}
if (avatarBackgroundColor != Color.TRANSPARENT) {
canvas.drawCircle(
avatarDrawableRect.centerX(),
avatarDrawableRect.centerY(),
drawableRadius,
circleBackgroundPaint
)
}
val avatarDrawable = this.avatarDrawable
if (null != avatarDrawable && hasAvatar()) {
canvas.drawCircle(
avatarDrawableRect.centerX(),
avatarDrawableRect.centerY(),
drawableRadius,
bitmapPaint
)
} else if (null != initials) {
canvas.drawText(
initials!!,
width.div(2f) - initialsRect.width().div(2f),
height.div(2f) + initialsRect.height().div(2f),
initialsPaint
)
}
if (middleThickness > 0) {
canvas.drawCircle(middleRect.centerX(), middleRect.centerY(), middleRadius, middlePaint)
}
drawBorder(canvas)
if (showBadge && badgeColor != Color.TRANSPARENT) {
var badgeCx = 0f
var badgeCy = 0f
when (badgePosition) {
BadgePosition.BOTTOM_RIGHT -> {
badgeCx = borderRect.right - badgeRadius
badgeCy = borderRect.bottom - badgeRadius
}
BadgePosition.BOTTOM_LEFT -> {
badgeCx = borderRect.left + badgeRadius
badgeCy = borderRect.bottom - badgeRadius
}
BadgePosition.TOP_RIGHT -> {
badgeCx = borderRect.right - badgeRadius
badgeCy = borderRect.top + badgeRadius
}
BadgePosition.TOP_LEFT -> {
badgeCx = borderRect.left + badgeRadius
badgeCy = borderRect.top + badgeRadius
}
}
if (badgeStrokeWidth > 0) {
canvas.drawCircle(badgeCx, badgeCy, badgeRadius, badgeStrokePaint)
}
canvas.drawCircle(badgeCx, badgeCy, badgeRadius - badgeStrokeWidth, badgePaint)
}
}
private fun hasAvatar(): Boolean {
val drawable = this.drawable
val hasTransparentDrawable = drawable is ColorDrawable && drawable.alpha == 0
return !hasTransparentDrawable
}
private fun drawBorder(canvas: Canvas) {
if (isAnimating || isReversedAnimating) {
val totalDegrees = (270f + animationDrawingState.rotationInDegrees) % 360
drawArches(totalDegrees, canvas)
val startOfMainArch = totalDegrees + (animationDrawingState.archesAreaInDegrees)
canvas.drawArc(
arcBorderRect,
startOfMainArch,
360 - animationDrawingState.archesAreaInDegrees,
false,
borderPaint
)
} else {
canvas.drawCircle(borderRect.centerX(), borderRect.centerY(), borderRadius, borderPaint)
}
}
private fun drawArches(totalDegrees: Float, canvas: Canvas) {
for (i in 0..numberOfArches) {
val deg =
totalDegrees + (spaceBetweenArches + individualArcDegreeLength) * i * (animationDrawingState.coercedArchesExpansionProgress)
canvas.drawArc(arcBorderRect, deg, individualArcDegreeLength, false, borderPaint)
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
setup()
}
override fun setPadding(left: Int, top: Int, right: Int, bottom: Int) {
super.setPadding(left, top, right, bottom)
setup()
}
override fun setPaddingRelative(start: Int, top: Int, end: Int, bottom: Int) {
super.setPaddingRelative(start, top, end, bottom)
setup()
}
private fun findInitials() {
text?.trim()?.let {
if (it.isNotBlank()) {
val words = it.split(' ')
var initialsCount = 1
initials = words[0].first().toString()
if (words.size > 1) {
initialsCount++
initials = "$initials${words.last().first()}"
}
initialsPaint.getTextBounds(initials, 0, initialsCount, initialsRect)
}
}
}
/**
* This section makes the elevation settings on Lollipop+ possible,
* drawing a circlar shadow around the border
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private inner class OutlineProvider : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) = Rect().let {
borderRect.roundOut(it)
outline.setRoundRect(it, it.width() / 2.0f)
}
}
data class AnimationDrawingState(
private val archesExpansionProgress: Float,
private val rotationProgress: Float,
) {
val coercedArchesExpansionProgress: Float
val coercedRotationProgress: Float
init {
this.coercedArchesExpansionProgress =
archesExpansionProgress.coerceIn(MIN_VALUE, MAX_VALUE)
this.coercedRotationProgress = rotationProgress.coerceIn(MIN_VALUE, MAX_VALUE)
}
companion object {
const val MAX_VALUE = 1f
const val MIN_VALUE = 0f
}
}
inner class AnimatorInterface {
private val currentAnimationState: AnimationDrawingState
get() = animationDrawingState
fun updateAnimationState(update: (currentState: AnimationDrawingState) -> AnimationDrawingState) {
animationDrawingState = update(currentAnimationState)
invalidate()
}
}
}
================================================
FILE: avvylib/src/main/java/xyz/schwaab/avvylib/BadgePosition.kt
================================================
package xyz.schwaab.avvylib
/**
* Defines the badge positions that can be used
* @see [AvatarView.badgePosition]
*/
enum class BadgePosition {
/**
* Position the badge at bottom-right corner
*/
BOTTOM_RIGHT,
/**
* Position the badge at bottom-left corner
*/
BOTTOM_LEFT,
/**
* Position the badge at top-right corner
*/
TOP_RIGHT,
/**
* Position the badge at top-left corner
*/
TOP_LEFT
}
================================================
FILE: avvylib/src/main/java/xyz/schwaab/avvylib/Defaults.kt
================================================
package xyz.schwaab.avvylib
import android.graphics.Bitmap
import android.graphics.Color
import android.widget.ImageView
/**
* Created by vitor on 18/09/18.
*/
internal object Defaults {
val SCALE_TYPE = ImageView.ScaleType.CENTER_CROP
val BITMAP_CONFIG = Bitmap.Config.ARGB_8888
val BORDER_COLOR_HIGHLIGHT = Color.parseColor("#ffff6d00")
val BORDER_COLOR = Color.parseColor("#ff757575")
const val MIDDLE_COLOR = Color.TRANSPARENT
const val COLORDRAWABLE_DIMENSION = 2
const val BORDER_THICKNESS = 12
const val HIGHLIGHTED_BORDER_THICKNESS = 16
const val CIRCLE_BACKGROUND_COLOR = Color.TRANSPARENT
const val IS_HIGHLIGHTED = false
const val DISTANCE_TO_BORDER = 25
const val NUMBER_OF_ARCHES = 5
const val ARCHES_DEGREES_AREA = 90f
const val INDIVIDUAL_ARCH_DEGREES_LENGTH = 3f
const val SHOW_BADGE = false
const val BADGE_RADIUS = 8f
val BADGE_COLOR = Color.parseColor("#00FF00")
val BADGE_STROKE_COLOR = Color.parseColor("#FFFFFF")
}
================================================
FILE: avvylib/src/main/java/xyz/schwaab/avvylib/animation/AnimatorListenerUtils.kt
================================================
package xyz.schwaab.avvylib.animation
import android.animation.Animator
/**
* Created by vitor on 19/09/18.
*/
internal fun Animator.addOnAnimationEndListener(onEnd: ((Animator?) -> Unit)) {
addListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) = Unit
override fun onAnimationCancel(animation: Animator?) = Unit
override fun onAnimationStart(animation: Animator?) = Unit
override fun onAnimationEnd(animation: Animator?) {
onEnd(animation)
}
})
}
================================================
FILE: avvylib/src/main/java/xyz/schwaab/avvylib/animation/AvatarViewAnimationOrchestrator.kt
================================================
package xyz.schwaab.avvylib.animation
import android.animation.AnimatorSet
import xyz.schwaab.avvylib.AvatarView
/**
* @param setupAnimators These animators will run before the progressAnimators.
* When stopping the animations, these animators will be played in reverse, to animate back to the original state.
* It's really useful to expand/collapse the arches, manipulating the [AvatarView.AnimationDrawingState.archesExpansionProgress] parameter during animation
* @param progressAnimators These will e run after the setup animators.
* They will not be called in reverse, as they expected to repeat infinitely.
*/
class AvatarViewAnimationOrchestrator(
private val setupAnimators: List = listOf(),
private val progressAnimators: List = listOf(),
) {
constructor(setupAnimator: AvatarViewAnimator, progressAnimator: AvatarViewAnimator) : this(
listOf(setupAnimator),
listOf(progressAnimator)
)
val setupSet = AnimatorSet().apply {
val baseAnimators = setupAnimators.map { it.baseAnimator }
if (baseAnimators.isNotEmpty()) {
playTogether(*baseAnimators.toTypedArray())
}
}
/**
* These animators will be called
*/
val progressSet = AnimatorSet().apply {
val baseAnimators = progressAnimators.map { it.baseAnimator }
if (baseAnimators.isNotEmpty()) {
playTogether(*baseAnimators.toTypedArray())
}
}
val animatorSet = AnimatorSet().apply {
playSequentially(setupSet, progressSet)
}
internal fun cancel() {
animatorSet.cancel()
}
internal fun start() {
animatorSet.start()
}
internal fun reverse() {
setupAnimators.forEach { animator ->
animator.baseAnimator.reverse()
}
}
internal fun attach(
animatorInterface: AvatarView.AnimatorInterface,
onSetupEnd: () -> Unit = {}
) {
(setupAnimators + progressAnimators).forEach { animator ->
animator.baseAnimator.addUpdateListener {
animator.onValueUpdate(animatorInterface)
}
}
setupSet.addOnAnimationEndListener {
onSetupEnd()
}
}
}
================================================
FILE: avvylib/src/main/java/xyz/schwaab/avvylib/animation/AvatarViewAnimator.kt
================================================
package xyz.schwaab.avvylib.animation
import android.animation.ValueAnimator
import xyz.schwaab.avvylib.AvatarView
interface AvatarViewAnimator {
val baseAnimator: ValueAnimator
fun onValueUpdate(animatorInterface: AvatarView.AnimatorInterface)
}
================================================
FILE: avvylib/src/main/java/xyz/schwaab/avvylib/animation/DefaultAnimationOrchestrator.kt
================================================
package xyz.schwaab.avvylib.animation
import android.animation.ValueAnimator
import android.view.animation.LinearInterpolator
import xyz.schwaab.avvylib.AvatarView
object DefaultAnimationOrchestrator {
private const val DEFAULT_ROTATION_DURATION = 2000L
private const val DEFAULT_EXPANSION_DURATION = 250L
fun create(
rotationDurationInMillis: Long = DEFAULT_ROTATION_DURATION,
expandDurationInMillis: Long = DEFAULT_EXPANSION_DURATION
): AvatarViewAnimationOrchestrator {
val expansionAnimator = createDefaultExpansionAnimator(expandDurationInMillis)
val rotationAnimator = createDefaultRotationAnimator(rotationDurationInMillis)
return AvatarViewAnimationOrchestrator(expansionAnimator, rotationAnimator)
}
@Suppress("MemberVisibilityCanBePrivate")
fun createDefaultExpansionAnimator(expandDurationInMillis: Long): AvatarViewAnimator {
return object : AvatarViewAnimator {
override val baseAnimator = ValueAnimator.ofFloat(
AvatarView.AnimationDrawingState.MIN_VALUE,
AvatarView.AnimationDrawingState.MAX_VALUE
).apply {
interpolator = LinearInterpolator()
duration = expandDurationInMillis
}!!
override fun onValueUpdate(animatorInterface: AvatarView.AnimatorInterface) {
animatorInterface.updateAnimationState { state ->
val animatedValue = baseAnimator.animatedValue as Float
state.copy(archesExpansionProgress = animatedValue)
}
}
}
}
@Suppress("MemberVisibilityCanBePrivate")
fun createDefaultRotationAnimator(rotationDurationInMillis: Long): AvatarViewAnimator {
return object : AvatarViewAnimator {
override val baseAnimator: ValueAnimator = ValueAnimator.ofFloat(
AvatarView.AnimationDrawingState.MIN_VALUE,
AvatarView.AnimationDrawingState.MAX_VALUE
).apply {
repeatCount = ValueAnimator.INFINITE
duration = rotationDurationInMillis
interpolator = LinearInterpolator()
}!!
override fun onValueUpdate(animatorInterface: AvatarView.AnimatorInterface) {
animatorInterface.updateAnimationState { state ->
val animatedValue = baseAnimator.animatedValue as Float
state.copy(rotationProgress = animatedValue)
}
}
}
}
}
================================================
FILE: avvylib/src/main/res/values/attrs.xml
================================================
================================================
FILE: avvylib/src/main/res/values/strings.xml
================================================
Avvy Lib
================================================
FILE: avvylib/src/test/java/xyz/schwaab/avvylib/ExampleUnitTest.kt
================================================
package xyz.schwaab.avvylib
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).toLong())
}
}
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlinVersion = '1.6.21'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
subprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
================================================
FILE: buildSrc/.gitignore
================================================
/build
/.gradle
================================================
FILE: buildSrc/build.gradle.kts
================================================
plugins {
`kotlin-dsl`
}
repositories {
jcenter()
google()
}
================================================
FILE: buildSrc/src/main/java/AndroidModuleSpecs.kt
================================================
object AndroidModuleSpecs {
const val compileSdkVersion = 30
const val targetSdkVersion = 30
const val minSdkVersion = 14
}
================================================
FILE: convention-plugins/build.gradle.kts
================================================
plugins {
`kotlin-dsl`
}
repositories {
gradlePluginPortal()
}
================================================
FILE: convention-plugins/src/main/kotlin/convention.publication.gradle.kts
================================================
import java.util.Properties
plugins {
`maven-publish`
signing
}
// Stub secrets to let the project sync and build without the publication values set up
ext["signing.keyId"] = null
ext["signing.password"] = null
ext["signing.secretKeyRingFile"] = null
ext["ossrhUsername"] = null
ext["ossrhPassword"] = null
// Grabbing secrets from local.properties file or from environment variables, which could be used on CI
val secretPropsFile = project.rootProject.file("local.properties")
if (secretPropsFile.exists()) {
secretPropsFile.reader().use {
Properties().apply { load(it) }
}.onEach { (name, value) ->
ext[name.toString()] = value
}
} else {
ext["signing.keyId"] = System.getenv("SIGNING_KEY_ID")
ext["signing.password"] = System.getenv("SIGNING_PASSWORD")
ext["signing.secretKeyRingFile"] = System.getenv("SIGNING_SECRET_KEY_RING_FILE")
ext["ossrhUsername"] = System.getenv("OSSRH_USERNAME")
ext["ossrhPassword"] = System.getenv("OSSRH_PASSWORD")
}
fun getExtraString(name: String) = ext[name]?.toString()
publishing {
// Configure maven central repository
repositories {
maven {
name = "sonatype"
setUrl("https://oss.sonatype.org/service/local/staging/deploy/maven2/")
credentials {
username = getExtraString("ossrhUsername")
password = getExtraString("ossrhPassword")
}
}
}
// Configure all publications
publications.withType {
// Provide artifacts information requited by Maven Central
pom {
name.set("AvatarView")
description.set("A circular ImageView with border, progress animation and customizable highlights for Android")
url.set("https://github.com/vitorhugods/AvatarView")
licenses {
license {
name.set("Apache-2.0")
url.set("https://opensource.org/licenses/Apache-2.0")
}
}
developers {
developer {
id.set("vitorhugods")
name.set("Vitor Hugo Schwaab")
email.set("vitor@schwaab.xyz")
}
}
scm {
url.set("https://github.com/vitorhugods/AvatarView")
}
}
}
}
// Signing artifacts. Signing.* extra properties values will be used
signing {
sign(publishing.publications)
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Sun Oct 11 23:02:27 CEST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
android.enableJetifier=true
android.useAndroidX=true
kotlin.code.style=official
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: settings.gradle.kts
================================================
// Demo app
include(":app")
// Library
include(":avvylib")
// Build and Publishing tools
includeBuild("convention-plugins")