├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── layout
│ │ │ │ ├── activity_main.xml
│ │ │ │ └── item_drawable_spec.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── top
│ │ │ │ └── defaults
│ │ │ │ └── drawabletoolboxapp
│ │ │ │ ├── DrawableFactory.kt
│ │ │ │ ├── spec
│ │ │ │ ├── DrawableSpec.kt
│ │ │ │ ├── TextViewBackgroundDrawableSpec.kt
│ │ │ │ ├── SegmentedControlDrawableSpec.kt
│ │ │ │ └── ImageViewSourceDrawableSpec.kt
│ │ │ │ ├── App.kt
│ │ │ │ ├── CheckerboardRelativeLayout.kt
│ │ │ │ ├── MainActivity.kt
│ │ │ │ ├── DrawableSpecAdapter.kt
│ │ │ │ └── SampleCodeSnippets.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── top
│ │ │ └── defaults
│ │ │ └── drawabletoolboxapp
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── top
│ │ └── defaults
│ │ └── drawabletoolboxapp
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── drawabletoolbox
├── .gitignore
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── top
│ │ │ └── defaults
│ │ │ └── drawabletoolbox
│ │ │ ├── Constants.kt
│ │ │ ├── DrawableWrapperBuilder.kt
│ │ │ ├── FlipDrawableBuilder.kt
│ │ │ ├── ScaleDrawableBuilder.kt
│ │ │ ├── RotateDrawableBuilder.kt
│ │ │ ├── PathShapeDrawableBuilder.kt
│ │ │ ├── StateListDrawableBuilder.kt
│ │ │ ├── FlipDrawable.kt
│ │ │ ├── RippleDrawableBuilder.kt
│ │ │ ├── LayerDrawableBuilder.kt
│ │ │ ├── Compatible.kt
│ │ │ ├── DrawableProperties.kt
│ │ │ └── DrawableBuilder.kt
│ ├── test
│ │ └── java
│ │ │ └── top
│ │ │ └── defaults
│ │ │ └── drawabletoolbox
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── top
│ │ └── defaults
│ │ └── drawabletoolbox
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── art
├── sample-1.png
├── sample-10.png
├── sample-11.png
├── sample-12.png
├── sample-13.png
├── sample-14.png
├── sample-15.png
├── sample-2.png
├── sample-3.png
├── sample-4.png
├── sample-5.png
├── sample-6.png
├── sample-7.png
├── sample-8.png
├── sample-9.png
├── screen-shot-1.jpg
├── screen-shot-2.jpg
├── screen-video-1.gif
└── screen-video-2.gif
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── encodings.xml
├── vcs.xml
├── compiler.xml
├── modules.xml
├── runConfigurations.xml
├── codeStyles
│ └── Project.xml
└── misc.xml
├── gradle.properties
├── .gitignore
├── gradlew.bat
├── gradlew
├── README_cn.md
├── README.md
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/drawabletoolbox/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':drawabletoolbox'
2 |
--------------------------------------------------------------------------------
/art/sample-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-1.png
--------------------------------------------------------------------------------
/art/sample-10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-10.png
--------------------------------------------------------------------------------
/art/sample-11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-11.png
--------------------------------------------------------------------------------
/art/sample-12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-12.png
--------------------------------------------------------------------------------
/art/sample-13.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-13.png
--------------------------------------------------------------------------------
/art/sample-14.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-14.png
--------------------------------------------------------------------------------
/art/sample-15.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-15.png
--------------------------------------------------------------------------------
/art/sample-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-2.png
--------------------------------------------------------------------------------
/art/sample-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-3.png
--------------------------------------------------------------------------------
/art/sample-4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-4.png
--------------------------------------------------------------------------------
/art/sample-5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-5.png
--------------------------------------------------------------------------------
/art/sample-6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-6.png
--------------------------------------------------------------------------------
/art/sample-7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-7.png
--------------------------------------------------------------------------------
/art/sample-8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-8.png
--------------------------------------------------------------------------------
/art/sample-9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/sample-9.png
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/art/screen-shot-1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/screen-shot-1.jpg
--------------------------------------------------------------------------------
/art/screen-shot-2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/screen-shot-2.jpg
--------------------------------------------------------------------------------
/art/screen-video-1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/screen-video-1.gif
--------------------------------------------------------------------------------
/art/screen-video-2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/art/screen-video-2.gif
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/duanhong169/DrawableToolbox/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/Constants.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | class Constants {
4 |
5 | companion object {
6 | const val DEFAULT_COLOR = 0xFFBA68C8.toInt()
7 | }
8 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Jul 31 10:19:42 CST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | DrawableToolbox
3 | Drawable Host
4 | Animate
5 | Item 1
6 | Item 2
7 | Item 3
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/DrawableFactory.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp
2 |
3 | import android.graphics.drawable.Drawable
4 | import top.defaults.drawabletoolboxapp.spec.DrawableSpec
5 |
6 | interface DrawableFactory {
7 |
8 | fun build(drawableSpec: DrawableSpec, index: Int = 0): Drawable = build()
9 |
10 | fun build(): Drawable
11 | }
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/spec/DrawableSpec.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp.spec
2 |
3 | import android.graphics.drawable.Drawable
4 | import top.defaults.drawabletoolboxapp.DrawableFactory
5 |
6 | open class DrawableSpec(var name: String, private val factory: DrawableFactory) {
7 |
8 | open fun build(index: Int = 0): Drawable = factory.build(this, index)
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/App.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp
2 |
3 | import android.app.Application
4 | import android.content.Context
5 | import me.weishu.reflection.Reflection
6 |
7 | class App: Application() {
8 |
9 | override fun attachBaseContext(base: Context) {
10 | super.attachBaseContext(base)
11 | Reflection.unseal(base)
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/spec/TextViewBackgroundDrawableSpec.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp.spec
2 |
3 | import top.defaults.drawabletoolboxapp.DrawableFactory
4 |
5 | class TextViewBackgroundDrawableSpec(name: String, factory: DrawableFactory) : DrawableSpec(name, factory) {
6 |
7 | var isDarkBackground: Boolean = false
8 | fun isDarkBackground(boolean: Boolean = true) = apply { isDarkBackground = boolean }
9 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #BA68C8
4 | #9C27B0
5 | #F44336
6 | #B71C1C
7 | #22000000
8 | #22FFFFFF
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/DrawableWrapperBuilder.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.graphics.drawable.Drawable
4 |
5 | abstract class DrawableWrapperBuilder> {
6 |
7 | protected var drawable: Drawable? = null
8 |
9 | @Suppress("UNCHECKED_CAST")
10 | fun drawable(drawable: Drawable): T = apply { this.drawable = drawable } as T
11 |
12 | abstract fun build(): Drawable
13 | }
--------------------------------------------------------------------------------
/app/src/test/java/top/defaults/drawabletoolboxapp/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/test/java/top/defaults/drawabletoolbox/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/FlipDrawableBuilder.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.graphics.drawable.Drawable
4 |
5 | class FlipDrawableBuilder: DrawableWrapperBuilder() {
6 |
7 | private var orientation: Int = FlipDrawable.ORIENTATION_HORIZONTAL
8 |
9 | fun orientation(orientation: Int) = apply { this.orientation = orientation }
10 |
11 | override fun build(): Drawable {
12 | return FlipDrawable(drawable!!, orientation)
13 | }
14 | }
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/CheckerboardRelativeLayout.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.widget.RelativeLayout
6 |
7 | import top.defaults.checkerboarddrawable.CheckerboardDrawable
8 |
9 | class CheckerboardRelativeLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr) {
10 |
11 | init {
12 | val drawable = CheckerboardDrawable.Builder().size(30).build()
13 | setBackgroundDrawable(drawable)
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/spec/SegmentedControlDrawableSpec.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp.spec
2 |
3 | import top.defaults.drawabletoolboxapp.DrawableFactory
4 |
5 | class SegmentedControlDrawableSpec(name: String, factory: DrawableFactory) : DrawableSpec(name, factory) {
6 |
7 | companion object {
8 | const val TYPE_LEFT_MOST = 1
9 | const val TYPE_MIDDLE = 2
10 | const val TYPE_RIGHT_MOST = 3
11 | }
12 |
13 | var itemCount = 3
14 | var selectedIndex: Int = 0
15 |
16 | fun getType(index: Int): Int {
17 | return when(index) {
18 | 0 -> TYPE_LEFT_MOST
19 | itemCount - 1 -> TYPE_RIGHT_MOST
20 | else -> TYPE_MIDDLE
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp
2 |
3 | import android.support.v7.app.AppCompatActivity
4 | import android.os.Bundle
5 | import android.support.v7.widget.LinearLayoutManager
6 | import android.support.v7.widget.RecyclerView
7 |
8 | class MainActivity : AppCompatActivity() {
9 |
10 | override fun onCreate(savedInstanceState: Bundle?) {
11 | super.onCreate(savedInstanceState)
12 | setContentView(R.layout.activity_main)
13 |
14 | val list = findViewById(R.id.drawableSpecList)
15 | val layoutManager = LinearLayoutManager(this)
16 | list.layoutManager = layoutManager
17 | val adapter = DrawableSpecAdapter(samples(this))
18 | list.adapter = adapter
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/top/defaults/drawabletoolboxapp/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getTargetContext()
22 | assertEquals("top.defaults.drawabletoolboxapp", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/drawabletoolbox/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/spec/ImageViewSourceDrawableSpec.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp.spec
2 |
3 | import android.animation.ValueAnimator
4 | import top.defaults.drawabletoolboxapp.DrawableFactory
5 |
6 | class ImageViewSourceDrawableSpec(name: String, factory: DrawableFactory) : DrawableSpec(name, factory) {
7 |
8 | var initialLevel: Int = 10000
9 | var animationRepeatMode: Int = -1
10 | var animationEnabled: Boolean = false
11 |
12 | fun initialLevel(level: Int) = apply { initialLevel = level }
13 | fun animateRestart() = apply { animationRepeatMode = ValueAnimator.RESTART }
14 | fun animateReverse() = apply { animationRepeatMode = ValueAnimator.REVERSE }
15 | fun shouldAnimate(): Boolean { return animationEnabled && animationRepeatMode > 0 }
16 | fun canAnimate(): Boolean { return animationRepeatMode > 0 }
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
19 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/androidTest/java/top/defaults/drawabletoolbox/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("top.defaults.drawabletoolbox.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/ScaleDrawableBuilder.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.graphics.drawable.Drawable
4 | import android.graphics.drawable.ScaleDrawable
5 | import android.view.Gravity
6 |
7 | class ScaleDrawableBuilder: DrawableWrapperBuilder() {
8 |
9 | private var level: Int = 10000
10 | private var scaleGravity = Gravity.CENTER
11 | private var scaleWidth: Float = 0f
12 | private var scaleHeight: Float = 0f
13 |
14 | fun level(level: Int) = apply { this.level = level }
15 | fun scaleGravity(gravity: Int) = apply { this.scaleGravity = gravity }
16 | fun scaleWidth(scale: Float) = apply { this.scaleWidth = scale }
17 | fun scaleHeight(scale: Float) = apply { this.scaleHeight = scale }
18 |
19 | override fun build(): Drawable {
20 | val scaleDrawable = ScaleDrawable(drawable, scaleGravity, scaleWidth, scaleHeight)
21 | scaleDrawable.level = level
22 | return scaleDrawable
23 | }
24 | }
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/RotateDrawableBuilder.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.graphics.drawable.Drawable
4 | import android.graphics.drawable.RotateDrawable
5 |
6 | class RotateDrawableBuilder: DrawableWrapperBuilder() {
7 |
8 | private var pivotX: Float = 0.5f
9 | private var pivotY: Float = 0.5f
10 | private var fromDegrees: Float = 0f
11 | private var toDegrees: Float = 360f
12 |
13 | fun pivotX(x: Float) = apply { pivotX = x }
14 | fun pivotY(y: Float) = apply { pivotY = y }
15 | fun fromDegrees(degree: Float) = apply { fromDegrees = degree }
16 | fun toDegrees(degree: Float) = apply { toDegrees = degree }
17 |
18 | override fun build(): Drawable {
19 | val rotateDrawable = RotateDrawable()
20 | drawable?.let {
21 | setDrawable(rotateDrawable, it)
22 | apply {
23 | setPivotX(rotateDrawable, pivotX)
24 | setPivotY(rotateDrawable, pivotY)
25 | setFromDegrees(rotateDrawable, fromDegrees)
26 | setToDegrees(rotateDrawable, toDegrees)
27 | }
28 | }
29 | return rotateDrawable
30 | }
31 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # IntelliJ
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/dictionaries
41 | .idea/libraries
42 | .idea/caches
43 |
44 | # Keystore files
45 | # Uncomment the following line if you do not want to check your keystore files in.
46 | #*.jks
47 |
48 | # External native build folder generated in Android Studio 2.2 and later
49 | .externalNativeBuild
50 |
51 | # Google Services (e.g. APIs or Firebase)
52 | google-services.json
53 |
54 | # Freeline
55 | freeline.py
56 | freeline/
57 | freeline_project_description.json
58 |
59 | # fastlane
60 | fastlane/report.xml
61 | fastlane/Preview.html
62 | fastlane/screenshots
63 | fastlane/test_output
64 | fastlane/readme.md
65 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/PathShapeDrawableBuilder.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.graphics.Path
4 | import android.graphics.drawable.ShapeDrawable
5 | import android.graphics.drawable.shapes.PathShape
6 |
7 | class PathShapeDrawableBuilder {
8 |
9 | private var path: Path? = null
10 | private var pathStandardWidth: Float = 100f
11 | private var pathStandardHeight: Float = 100f
12 | private var width: Int = -1
13 | private var height: Int = -1
14 |
15 | fun path(path: Path, pathStandardWidth: Float, pathStandardHeight: Float) = apply {
16 | this.path = path
17 | this.pathStandardWidth = pathStandardWidth
18 | this.pathStandardHeight = pathStandardHeight
19 | }
20 |
21 | fun width(width: Int) = apply { this.width = width }
22 | fun height(height: Int) = apply { this.height = height }
23 | fun size(size: Int) = apply { width(size).height(size) }
24 |
25 | fun build(custom: ((shapeDrawable: ShapeDrawable) -> Unit)? = null): ShapeDrawable {
26 | val shapeDrawable = ShapeDrawable()
27 | if (path == null || width <= 0 || height <= 0) {
28 | return shapeDrawable
29 | }
30 | val pathShape = PathShape(path, pathStandardWidth, pathStandardHeight)
31 |
32 | shapeDrawable.shape = pathShape
33 | shapeDrawable.intrinsicWidth = width
34 | shapeDrawable.intrinsicHeight = height
35 | if (custom != null) {
36 | custom(shapeDrawable)
37 | }
38 | return shapeDrawable
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/StateListDrawableBuilder.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.graphics.Color
4 | import android.graphics.drawable.ColorDrawable
5 | import android.graphics.drawable.Drawable
6 | import android.graphics.drawable.StateListDrawable
7 | import android.util.StateSet
8 |
9 | class StateListDrawableBuilder {
10 |
11 | private var pressed: Drawable? = null
12 | private var disabled: Drawable? = null
13 | private var selected: Drawable? = null
14 | private var normal: Drawable = ColorDrawable(Color.TRANSPARENT)
15 |
16 | fun pressed(pressed: Drawable?) = apply { this.pressed = pressed }
17 | fun disabled(disabled: Drawable?) = apply { this.disabled = disabled }
18 | fun selected(selected: Drawable?) = apply { this.selected = selected }
19 | fun normal(normal: Drawable) = apply { this.normal = normal }
20 |
21 | fun build(): StateListDrawable {
22 | val stateListDrawable = StateListDrawable()
23 | setupStateListDrawable(stateListDrawable)
24 | return stateListDrawable
25 | }
26 |
27 | private fun setupStateListDrawable(stateListDrawable: StateListDrawable) {
28 | pressed?.let {
29 | stateListDrawable.addState(intArrayOf(android.R.attr.state_pressed), it)
30 | }
31 | disabled?.let {
32 | stateListDrawable.addState(intArrayOf(-android.R.attr.state_enabled), it)
33 | }
34 | selected?.let {
35 | stateListDrawable.addState(intArrayOf(android.R.attr.state_selected), it)
36 | }
37 | stateListDrawable.addState(StateSet.WILD_CARD, normal)
38 | }
39 | }
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 28
7 | defaultConfig {
8 | applicationId "top.defaults.drawabletoolboxapp"
9 | minSdkVersion 14
10 | targetSdkVersion 28
11 | versionCode 1
12 | versionName "1.0"
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 | }
15 | compileOptions {
16 | sourceCompatibility JavaVersion.VERSION_1_8
17 | targetCompatibility JavaVersion.VERSION_1_8
18 | }
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(include: ['*.jar'], dir: 'libs')
29 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
30 | implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
31 | implementation 'com.android.support:recyclerview-v7:28.0.0-rc02'
32 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
33 | implementation 'me.weishu:free_reflection:1.2.0'
34 | implementation 'com.github.duanhong169:text-button:1.0.5'
35 | implementation 'com.github.duanhong169:checkerboarddrawable:1.0.2'
36 | // implementation 'com.github.duanhong169:drawabletoolbox:1.0.7'
37 | implementation project(':drawabletoolbox')
38 | testImplementation 'junit:junit:4.12'
39 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
40 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
41 | }
42 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/FlipDrawable.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.graphics.Canvas
4 | import android.graphics.ColorFilter
5 | import android.graphics.Rect
6 | import android.graphics.drawable.Drawable
7 |
8 | class FlipDrawable(private var drawable: Drawable, private var orientation: Int = ORIENTATION_HORIZONTAL) : Drawable() {
9 |
10 | companion object {
11 | const val ORIENTATION_HORIZONTAL = 0
12 | const val ORIENTATION_VERTICAL = 1
13 | }
14 |
15 | override fun draw(canvas: Canvas) {
16 | val saveCount = canvas.save()
17 | if (orientation == ORIENTATION_VERTICAL) {
18 | canvas.scale(1f, -1f, (canvas.width / 2).toFloat(), (canvas.height / 2).toFloat())
19 | } else {
20 | canvas.scale(-1f, 1f, (canvas.width / 2).toFloat(), (canvas.height / 2).toFloat())
21 | }
22 | drawable.bounds = Rect(0, 0, canvas.width, canvas.height)
23 | drawable.draw(canvas)
24 | canvas.restoreToCount(saveCount)
25 | }
26 |
27 | override fun onLevelChange(level: Int): Boolean {
28 | drawable.level = level
29 | invalidateSelf()
30 | return true
31 | }
32 |
33 | override fun getIntrinsicWidth(): Int {
34 | return drawable.intrinsicWidth
35 | }
36 |
37 | override fun getIntrinsicHeight(): Int {
38 | return drawable.intrinsicHeight
39 | }
40 |
41 | override fun setAlpha(alpha: Int) {
42 | drawable.alpha = alpha
43 | }
44 |
45 | override fun getOpacity(): Int {
46 | return drawable.opacity
47 | }
48 |
49 | override fun setColorFilter(colorFilter: ColorFilter?) {
50 | drawable.colorFilter = colorFilter
51 | }
52 | }
--------------------------------------------------------------------------------
/drawabletoolbox/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 |
4 | ext {
5 | bintrayRepo = 'Hong'
6 | bintrayName = 'drawabletoolbox'
7 |
8 | publishedGroupId = 'com.github.duanhong169'
9 | artifact = 'drawabletoolbox'
10 |
11 | libraryName = 'DrawableToolbox'
12 | libraryDescription = 'The missing DrawableToolbox for Android'
13 | libraryVersion = '1.0.7'
14 |
15 | gitUrl = 'https://github.com/duanhong169/DrawableToolbox.git'
16 | siteUrl = 'https://github.com/duanhong169/DrawableToolbox'
17 |
18 | licenseName = 'Apache License 2.0'
19 | licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
20 | allLicenses = ["Apache-2.0"]
21 | }
22 |
23 | android {
24 | compileSdkVersion 27
25 |
26 | defaultConfig {
27 | minSdkVersion 14
28 | targetSdkVersion 27
29 | versionCode 1
30 | versionName "1.0"
31 |
32 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
33 | }
34 |
35 | buildTypes {
36 | release {
37 | minifyEnabled false
38 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
39 | }
40 | }
41 |
42 | }
43 |
44 | dependencies {
45 | implementation fileTree(dir: 'libs', include: ['*.jar'])
46 |
47 | implementation 'com.android.support:appcompat-v7:27.1.1'
48 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
49 | testImplementation 'junit:junit:4.12'
50 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
51 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
52 | }
53 | repositories {
54 | mavenCentral()
55 | }
56 |
57 | apply from: 'https://raw.githubusercontent.com/duanhong169/bintray-gradle/master/bintray.gradle'
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/RippleDrawableBuilder.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.content.res.ColorStateList
4 | import android.graphics.Color
5 | import android.graphics.drawable.*
6 | import android.os.Build
7 | import android.util.StateSet
8 |
9 | class RippleDrawableBuilder: DrawableWrapperBuilder() {
10 |
11 | private var color: Int = Constants.DEFAULT_COLOR
12 | private var colorStateList: ColorStateList? = null
13 | private var radius: Int = -1
14 |
15 | fun color(color: Int) = apply { this.color = color }
16 | fun colorStateList(colorStateList: ColorStateList?) = apply { this.colorStateList = colorStateList }
17 | fun radius(radius: Int) = apply { this.radius = radius }
18 |
19 | override fun build(): Drawable {
20 | var drawable = this.drawable!!
21 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
22 | val colorStateList = this.colorStateList ?: ColorStateList(
23 | arrayOf(StateSet.WILD_CARD),
24 | intArrayOf(color)
25 | )
26 |
27 | var mask = if (drawable is DrawableContainer) drawable.getCurrent() else drawable
28 | if (mask is ShapeDrawable) {
29 | val state = mask.getConstantState()
30 | if (state != null) {
31 | val temp = state.newDrawable().mutate() as ShapeDrawable
32 | temp.paint.color = Color.BLACK
33 | mask = temp
34 | }
35 | } else if (mask is GradientDrawable) {
36 | val state = mask.getConstantState()
37 | if (state != null) {
38 | val temp = state.newDrawable().mutate() as GradientDrawable
39 | temp.setColor(Color.BLACK)
40 | mask = temp
41 | }
42 | } else {
43 | mask = ColorDrawable(Color.BLACK)
44 | }
45 |
46 | val rippleDrawable = RippleDrawable(colorStateList, drawable, mask)
47 | setRadius(rippleDrawable, radius)
48 | rippleDrawable.invalidateSelf()
49 | drawable = rippleDrawable
50 | }
51 | return drawable
52 | }
53 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_drawable_spec.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
15 |
16 |
29 |
30 |
40 |
41 |
42 |
43 |
53 |
54 |
60 |
61 |
70 |
71 |
80 |
81 |
90 |
91 |
92 |
93 |
100 |
101 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
11 |
16 |
21 |
26 |
31 |
36 |
41 |
46 |
51 |
56 |
61 |
66 |
71 |
76 |
81 |
86 |
91 |
96 |
101 |
106 |
111 |
116 |
121 |
126 |
131 |
136 |
141 |
146 |
151 |
156 |
161 |
166 |
171 |
172 |
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/DrawableSpecAdapter.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp
2 |
3 | import android.animation.ObjectAnimator
4 | import android.animation.ValueAnimator
5 | import android.graphics.Color
6 | import android.support.v7.widget.RecyclerView
7 | import android.view.LayoutInflater
8 | import android.view.View
9 | import android.view.ViewGroup
10 | import android.view.animation.LinearInterpolator
11 | import android.widget.*
12 | import top.defaults.drawabletoolboxapp.spec.DrawableSpec
13 | import top.defaults.drawabletoolboxapp.spec.ImageViewSourceDrawableSpec
14 | import top.defaults.drawabletoolboxapp.spec.SegmentedControlDrawableSpec
15 | import top.defaults.drawabletoolboxapp.spec.TextViewBackgroundDrawableSpec
16 |
17 | class DrawableSpecAdapter(private val drawableSpecList: List) : RecyclerView.Adapter() {
18 |
19 | private var onItemClickListener: OnItemClickListener? = null
20 |
21 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
22 | val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_drawable_spec, parent, false)
23 | return ViewHolder(itemView)
24 | }
25 |
26 | override fun onBindViewHolder(holder: ViewHolder, position: Int) {
27 | holder.bind(getItem(position), position)
28 | }
29 |
30 | override fun getItemCount(): Int {
31 | return drawableSpecList.size
32 | }
33 |
34 | private fun getItem(position: Int): DrawableSpec {
35 | return drawableSpecList[position]
36 | }
37 |
38 | interface OnItemClickListener {
39 | fun onItemClick(view: View, position: Int)
40 | }
41 |
42 | fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
43 | this.onItemClickListener = onItemClickListener
44 | }
45 |
46 | inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
47 |
48 | private val nameTextView: TextView
49 | private val imageViewBoard: View
50 | private val imageView: ImageView
51 | private val animateCheckBox: CheckBox
52 | private val button: TextView
53 | private val segmentedControl: LinearLayout
54 | private var animator: ObjectAnimator? = null
55 |
56 | init {
57 | itemView.setOnClickListener { v -> onItemClickListener?.onItemClick(v, adapterPosition) }
58 | nameTextView = itemView.findViewById(R.id.name)
59 | imageViewBoard = itemView.findViewById(R.id.imageViewBoard)
60 | imageView = itemView.findViewById(R.id.imageView)
61 | animateCheckBox = itemView.findViewById(R.id.animateCheckBox)
62 | button = itemView.findViewById(R.id.button)
63 | segmentedControl = itemView.findViewById(R.id.segmentedControl)
64 | }
65 |
66 | fun bind(drawableSpec: DrawableSpec, position: Int) {
67 | animator?.run {
68 | cancel()
69 | }
70 |
71 | nameTextView.text = drawableSpec.name
72 | nameTextView.visibility = View.GONE
73 | imageViewBoard.visibility = View.GONE
74 | button.visibility = View.GONE
75 | segmentedControl.visibility = View.GONE
76 | when (drawableSpec) {
77 | is ImageViewSourceDrawableSpec -> {
78 | val drawable = drawableSpec.build()
79 |
80 | nameTextView.visibility = View.VISIBLE
81 | imageViewBoard.visibility = View.VISIBLE
82 | imageView.setImageDrawable(drawable)
83 | imageView.setImageLevel(drawableSpec.initialLevel)
84 | animateCheckBox.visibility = if (drawableSpec.canAnimate()) View.VISIBLE else View.INVISIBLE
85 | if (drawableSpec.canAnimate()) {
86 | animateCheckBox.setOnCheckedChangeListener(null)
87 | animateCheckBox.isChecked = drawableSpec.animationEnabled
88 | animateCheckBox.setOnCheckedChangeListener { _, isChecked ->
89 | drawableSpec.animationEnabled = isChecked
90 | notifyItemChanged(position)
91 | }
92 | }
93 |
94 | if (drawableSpec.shouldAnimate()) {
95 | animator = ObjectAnimator.ofInt(drawable, "level", 10000, 0)
96 | animator?.run {
97 | repeatCount = ValueAnimator.INFINITE
98 | repeatMode = drawableSpec.animationRepeatMode
99 | duration = 3000
100 | interpolator = LinearInterpolator()
101 | start()
102 | }
103 | }
104 | }
105 | is TextViewBackgroundDrawableSpec -> {
106 | button.visibility = View.VISIBLE
107 | button.setBackgroundDrawable(drawableSpec.build())
108 | button.text = drawableSpec.name
109 | if (drawableSpec.isDarkBackground) {
110 | button.setTextColor(Color.WHITE)
111 | } else {
112 | button.setTextColor(COLOR_DEFAULT_DARK)
113 | }
114 | }
115 | is SegmentedControlDrawableSpec -> {
116 | segmentedControl.visibility = View.VISIBLE
117 | val itemCount = segmentedControl.childCount
118 | for (i in 0 until itemCount) {
119 | val textView = segmentedControl.getChildAt(i) as TextView
120 | textView.setBackgroundDrawable(drawableSpec.build(i))
121 | textView.isSelected = i == drawableSpec.selectedIndex
122 | if (i == drawableSpec.selectedIndex) {
123 | textView.setTextColor(Color.WHITE)
124 | } else {
125 | textView.setTextColor(COLOR_DEFAULT_DARK)
126 | }
127 | textView.setOnClickListener {
128 | drawableSpec.selectedIndex = i
129 | notifyItemChanged(position)
130 | }
131 | }
132 | }
133 | }
134 | }
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/LayerDrawableBuilder.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.graphics.drawable.Drawable
4 | import android.graphics.drawable.LayerDrawable
5 | import android.os.Build
6 | import android.support.annotation.RequiresApi
7 | import android.view.Gravity
8 | import java.util.ArrayList
9 |
10 | class LayerDrawableBuilder {
11 |
12 | companion object {
13 | const val DIMEN_UNDEFINED = Int.MIN_VALUE
14 | }
15 |
16 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
17 | private var paddingMode = LayerDrawable.PADDING_MODE_NEST
18 | private var paddingLeft = 0
19 | private var paddingTop = 0
20 | private var paddingRight = 0
21 | private var paddingBottom = 0
22 | private var paddingStart = 0
23 | private var paddingEnd = 0
24 | private val layers = ArrayList()
25 |
26 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
27 | fun paddingMode(mode: Int) = apply { paddingMode = mode }
28 | fun paddingLeft(padding: Int) = apply { paddingLeft = padding }
29 | fun paddingTop(padding: Int) = apply { paddingTop = padding }
30 | fun paddingRight(padding: Int) = apply { paddingRight = padding }
31 | fun paddingBottom(padding: Int) = apply { paddingBottom = padding }
32 | @RequiresApi(Build.VERSION_CODES.M)
33 | fun paddingStart(padding: Int) = apply { paddingStart = padding }
34 | @RequiresApi(Build.VERSION_CODES.M)
35 | fun paddingEnd(padding: Int) = apply { paddingEnd = padding }
36 | fun padding(padding: Int) = apply { paddingLeft(padding).paddingTop(padding).paddingRight(padding).paddingBottom(padding) }
37 | @RequiresApi(Build.VERSION_CODES.M)
38 | fun paddingRelative(padding: Int) = apply { paddingStart(padding).paddingTop(padding).paddingEnd(padding).paddingBottom(padding) }
39 |
40 | fun add(drawable: Drawable) = apply { layers.add(Layer(drawable)) }
41 |
42 | fun width(width: Int) = apply { layers.last().width = width }
43 | fun height(height: Int) = apply { layers.last().height = height }
44 |
45 | fun insetLeft(inset: Int) = apply { layers.last().insetLeft = inset }
46 | fun insetTop(inset: Int) = apply { layers.last().insetTop = inset }
47 | fun insetRight(inset: Int) = apply { layers.last().insetRight = inset }
48 | fun insetBottom(inset: Int) = apply { layers.last().insetBottom = inset }
49 | @RequiresApi(Build.VERSION_CODES.M)
50 | fun insetStart(inset: Int) = apply { layers.last().insetStart = inset }
51 | @RequiresApi(Build.VERSION_CODES.M)
52 | fun insetEnd(inset: Int) = apply { layers.last().insetEnd = inset }
53 | fun inset(inset: Int) = apply { insetLeft(inset).insetTop(inset).insetRight(inset).insetBottom(inset) }
54 | fun inset(insetLeft: Int, insetTop: Int, insetRight: Int, insetBottom: Int) = apply {
55 | insetLeft(insetLeft).insetTop(insetTop).insetRight(insetRight).insetBottom(insetBottom)
56 | }
57 | @RequiresApi(Build.VERSION_CODES.M)
58 | fun insetRelative(inset: Int) = apply { insetStart(inset).insetTop(inset).insetEnd(inset).insetBottom(inset) }
59 | @RequiresApi(Build.VERSION_CODES.M)
60 | fun insetRelative(insetStart: Int, insetTop: Int, insetEnd: Int, insetBottom: Int) = apply {
61 | insetStart(insetStart).insetTop(insetTop).insetEnd(insetEnd).insetBottom(insetBottom)
62 | }
63 |
64 | @RequiresApi(Build.VERSION_CODES.M)
65 | fun gravity(gravity: Int) = apply { layers.last().gravity = gravity }
66 |
67 | fun modify(index: Int, drawable: Drawable,
68 | width: Int = DIMEN_UNDEFINED,
69 | height: Int = DIMEN_UNDEFINED,
70 | insetLeft: Int = DIMEN_UNDEFINED,
71 | insetTop: Int = DIMEN_UNDEFINED,
72 | insetRight: Int = DIMEN_UNDEFINED,
73 | insetBottom: Int = DIMEN_UNDEFINED,
74 | insetStart: Int = DIMEN_UNDEFINED,
75 | insetEnd: Int = DIMEN_UNDEFINED) =
76 | apply {
77 | val layer = layers[index]
78 | layer.drawable = drawable
79 | if (width != DIMEN_UNDEFINED) layer.width = width
80 | if (height != DIMEN_UNDEFINED) layer.height = height
81 | if (insetLeft != DIMEN_UNDEFINED) layer.insetLeft = insetLeft
82 | if (insetTop != DIMEN_UNDEFINED) layer.insetTop = insetTop
83 | if (insetRight != DIMEN_UNDEFINED) layer.insetRight = insetRight
84 | if (insetBottom != DIMEN_UNDEFINED) layer.insetBottom = insetBottom
85 | if (insetStart != DIMEN_UNDEFINED) layer.insetStart = insetStart
86 | if (insetEnd != DIMEN_UNDEFINED) layer.insetEnd = insetEnd
87 | }
88 |
89 | fun build(): LayerDrawable {
90 | val layerDrawable = LayerDrawable(layers.map { it -> it.drawable }.toTypedArray())
91 | for (i in 0 until layers.size) {
92 | val layer = layers[i]
93 | layerDrawable.setLayerInset(i, layer.insetLeft, layer.insetTop, layer.insetRight, layer.insetBottom)
94 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
95 | if (layer.insetStart != DIMEN_UNDEFINED || layer.insetEnd != DIMEN_UNDEFINED) {
96 | layerDrawable.setLayerInsetRelative(i, layer.insetStart, layer.insetTop, layer.insetEnd, layer.insetBottom)
97 | }
98 | }
99 | layerDrawable.setId(i, i)
100 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
101 | layerDrawable.setLayerGravity(i, layer.gravity)
102 | layerDrawable.setLayerInsetStart(i, layer.insetStart)
103 | layerDrawable.setLayerInsetEnd(i, layer.insetEnd)
104 | }
105 | }
106 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
107 | layerDrawable.paddingMode = paddingMode
108 | }
109 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
110 | layerDrawable.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom)
111 | if (paddingStart != DIMEN_UNDEFINED || paddingEnd != DIMEN_UNDEFINED) {
112 | layerDrawable.setPaddingRelative(paddingStart, paddingTop, paddingEnd, paddingBottom)
113 | }
114 | }
115 |
116 | return layerDrawable
117 | }
118 |
119 | internal class Layer(var drawable: Drawable) {
120 | var gravity: Int = Gravity.NO_GRAVITY
121 | var width: Int = -1
122 | var height: Int = -1
123 | var insetLeft: Int = 0
124 | var insetTop: Int = 0
125 | var insetRight: Int = 0
126 | var insetBottom: Int = 0
127 | var insetStart: Int = DIMEN_UNDEFINED
128 | var insetEnd: Int = DIMEN_UNDEFINED
129 | }
130 | }
--------------------------------------------------------------------------------
/README_cn.md:
--------------------------------------------------------------------------------
1 | # DrawableToolbox
2 | [](https://github.com/duanhong169/DrawableToolbox/releases)
3 | [](https://developer.android.com/index.html)
4 |
5 | [](https://github.com/duanhong169/DrawableToolbox/blob/master/LICENSE)
6 | [](https://github.com/KotlinBy/awesome-kotlin)
7 |
8 | [English](README.md) | 中文
9 |
10 | 功能完备的Drawable工具箱,通过代码构建种类多样的Drawable,摆脱枯燥重复的`drawable.xml`文件。
11 |
12 |
13 |
14 |
15 | ## 功能
16 |
17 | * 通过代码构建Drawable
18 | * 支持``,``,``,``,``等类型的drawable
19 | * 支持镜面翻转(水平或垂直方向)
20 |
21 | ## 参与本项目
22 |
23 | * 如果你有需要的功能,请提[Issue](https://github.com/duanhong169/DrawableToolbox/issues)或[Pull request](https://github.com/duanhong169/DrawableToolbox/pulls)
24 |
25 | ## Gradle
26 |
27 | ```
28 | dependencies {
29 | implementation 'com.github.duanhong169:drawabletoolbox:${latestVersion}'
30 | ...
31 | }
32 | ```
33 |
34 | > 将上方的`${latestVersion}`替换为当前最新的版本号,最新版本号参见[releases](https://github.com/duanhong169/DrawableToolbox/releases)。
35 |
36 | ## 使用说明
37 |
38 | 通过`DrawableBuilder`来配置`Drawable`, 然后使用`build()`构建得到`Drawable`对象。
39 |
40 | > 完整支持的API请参见[DrawableBuilder.kt](https://github.com/duanhong169/DrawableToolbox/blob/master/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/DrawableBuilder.kt)。
41 |
42 | 如下是一些示例代码和对应得到的`Drawable`:
43 |
44 | 代码:
45 |
46 | ```kotlin
47 | DrawableBuilder()
48 | .rectangle()
49 | .hairlineBordered()
50 | .strokeColor(COLOR_DEFAULT)
51 | .strokeColorPressed(COLOR_PRESSED)
52 | .ripple()
53 | .build()
54 | ```
55 |
56 | 结果:
57 |
58 | 
59 |
60 | 代码:
61 |
62 | ```kotlin
63 | DrawableBuilder()
64 | .rectangle()
65 | .hairlineBordered()
66 | .mediumDashed()
67 | .strokeColor(COLOR_DEFAULT)
68 | .strokeColorPressed(COLOR_PRESSED)
69 | .ripple()
70 | .build()
71 | ```
72 |
73 | 结果:
74 |
75 | 
76 |
77 | 代码:
78 |
79 | ```kotlin
80 | DrawableBuilder()
81 | .rectangle()
82 | .rounded()
83 | .solidColor(COLOR_DEFAULT)
84 | .solidColorPressed(COLOR_PRESSED)
85 | .build()
86 | ```
87 |
88 | 结果:
89 |
90 | 
91 |
92 | 代码:
93 |
94 | ```kotlin
95 | DrawableBuilder()
96 | .rectangle()
97 | .hairlineBordered()
98 | .longDashed()
99 | .rounded()
100 | .strokeColor(COLOR_DEFAULT)
101 | .strokeColorPressed(COLOR_PRESSED)
102 | .ripple()
103 | .build()
104 | ```
105 |
106 | 结果:
107 |
108 | 
109 |
110 | 代码:
111 |
112 | ```kotlin
113 | DrawableBuilder()
114 | .rectangle()
115 | .rounded()
116 | .gradient()
117 | .linearGradient()
118 | .angle(90)
119 | .startColor(COLOR_DEFAULT)
120 | .endColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
121 | .ripple()
122 | .rippleColor(COLOR_PRESSED)
123 | .build()
124 | ```
125 |
126 | 结果:
127 |
128 | 
129 |
130 | 代码:
131 |
132 | ```kotlin
133 | val baseBuilder = DrawableBuilder()
134 | .rectangle()
135 | .rounded()
136 | .gradient()
137 | .gradientType(GradientDrawable.LINEAR_GRADIENT)
138 | .angle(90)
139 | val normalState = baseBuilder
140 | .startColor(COLOR_DEFAULT)
141 | .endColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
142 | .build()
143 | val pressedState = baseBuilder
144 | .startColor(COLOR_PRESSED)
145 | .endColor(ContextCompat.getColor(context, R.color.colorAccentDark))
146 | .build()
147 |
148 | StateListDrawableBuilder()
149 | .normal(normalState)
150 | .pressed(pressedState)
151 | .build()
152 | ```
153 |
154 | 结果:
155 |
156 | 
157 |
158 | 代码:
159 |
160 | ```kotlin
161 | val baseBuilder = DrawableBuilder()
162 | .rectangle()
163 | .rounded()
164 | .hairlineBordered()
165 | .strokeColor(COLOR_DEFAULT)
166 | .solidColorSelected(COLOR_DEFAULT)
167 | .ripple()
168 |
169 | return when(type) {
170 | SegmentedControlDrawableSpec.TYPE_LEFT_MOST -> {
171 | baseBuilder.topRightRadius(0)
172 | .bottomRightRadius(0)
173 | .build()
174 | }
175 | SegmentedControlDrawableSpec.TYPE_RIGHT_MOST -> {
176 | baseBuilder.topLeftRadius(0)
177 | .bottomLeftRadius(0)
178 | .build()
179 | }
180 | else -> {
181 | baseBuilder.cornerRadius(0).build()
182 | }
183 | }
184 | ```
185 |
186 | 结果:
187 |
188 | 
189 |
190 | 代码:
191 |
192 | ```kotlin
193 | val layer1 = DrawableBuilder()
194 | .size(200)
195 | .rectangle()
196 | .rounded()
197 | .hairlineBordered()
198 | .strokeColor(COLOR_DEFAULT)
199 | .strokeColorPressed(COLOR_PRESSED)
200 | .build()
201 | val layer2 = DrawableBuilder()
202 | .rectangle()
203 | .rounded()
204 | .solidColor(COLOR_DEFAULT)
205 | .build()
206 | val layer3 = DrawableBuilder()
207 | .rectangle()
208 | .rounded()
209 | .solidColor(Color.WHITE)
210 | .ripple()
211 | .rippleColor(COLOR_DEFAULT)
212 | .build()
213 | LayerDrawableBuilder()
214 | .add(layer1)
215 | .add(layer2)
216 | .inset(10)
217 | .add(layer3)
218 | .inset(20)
219 | .build()
220 | ```
221 |
222 | 结果:
223 |
224 | 
225 |
226 | 代码:
227 |
228 | ```kotlin
229 | val layer1 = DrawableBuilder()
230 | .size(180)
231 | .rectangle()
232 | .build()
233 | val layer2 = DrawableBuilder()
234 | .oval()
235 | .solidColor(COLOR_DEFAULT)
236 | .build()
237 | val layer3 = DrawableBuilder()
238 | .rectangle()
239 | .solidColor(COLOR_DEFAULT_DARK)
240 | .rotate(45f)
241 | .build()
242 | val layer4 = DrawableBuilder()
243 | .rectangle()
244 | .bottomLeftRadius(100)
245 | .solidColor(COLOR_DEFAULT_DARK)
246 | .build()
247 | val layer5 = DrawableBuilder()
248 | .oval()
249 | .solidColor(COLOR_DEFAULT)
250 | .build()
251 | val layerDrawable = LayerDrawableBuilder()
252 | .add(layer1)
253 | .add(layer2)
254 | .inset(20, 20, 100, 100)
255 | .add(layer3)
256 | .inset(100, 20, 20, 100)
257 | .add(layer4)
258 | .inset(20, 100, 100, 20)
259 | .add(layer5)
260 | .inset(100, 100, 20, 20)
261 | .build()
262 | DrawableBuilder()
263 | .baseDrawable(layerDrawable)
264 | .rotate(0f, 360f)
265 | .build()
266 | ```
267 |
268 | 结果:
269 |
270 | 
271 |
272 | 代码:
273 |
274 | ```kotlin
275 | // Rotate & Leveled the Ring
276 | DrawableBuilder()
277 | .size(200)
278 | .ring()
279 | .useLevelForRing()
280 | .solidColor(COLOR_DEFAULT)
281 | .innerRadiusRatio(3f)
282 | .thicknessRatio(10f)
283 | .rotate(0f, 720f)
284 | .build()
285 | ```
286 |
287 | 结果:
288 |
289 | 
290 |
291 | 代码:
292 |
293 | ```kotlin
294 | // Rotate, Sweep & Flip the Ring
295 | DrawableBuilder()
296 | .size(200)
297 | .ring()
298 | .innerRadiusRatio(3f)
299 | .thicknessRatio(10f)
300 | .gradient()
301 | .sweepGradient()
302 | .rotate(0f, 360f)
303 | .flip()
304 | .build()
305 | ```
306 |
307 | 结果:
308 |
309 | 
310 |
311 | 代码:
312 |
313 | ```kotlin
314 | // Rotate, Sweep & Scale the Oval with States
315 | val baseBuilder = DrawableBuilder()
316 | .size(400)
317 | .oval()
318 | .gradient()
319 | .sweepGradient()
320 | .rotate(0f, 360f)
321 | .scale(0.5f)
322 | .scaleGravity(Gravity.START or Gravity.TOP)
323 | val normalState = baseBuilder.build()
324 | val pressedState = baseBuilder
325 | .startColor(COLOR_PRESSED)
326 | .endColor(0x7FFFFFFF)
327 | .build()
328 | StateListDrawableBuilder()
329 | .normal(normalState)
330 | .pressed(pressedState)
331 | .build()
332 | ```
333 |
334 | 结果:
335 |
336 | 
337 |
338 | 更多的代码示例请查看[SampleCodeSnippets.kt](https://github.com/duanhong169/DrawableToolbox/blob/master/app/src/main/java/top/defaults/drawabletoolboxapp/SampleCodeSnippets.kt)。
339 |
340 | ## License
341 |
342 | Copyright 2018 Hong Duan
343 |
344 | Licensed under the Apache License, Version 2.0 (the "License");
345 | you may not use this file except in compliance with the License.
346 | You may obtain a copy of the License at
347 |
348 | http://www.apache.org/licenses/LICENSE-2.0
349 |
350 | Unless required by applicable law or agreed to in writing, software
351 | distributed under the License is distributed on an "AS IS" BASIS,
352 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
353 | See the License for the specific language governing permissions and
354 | limitations under the License.
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/Compatible.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.graphics.drawable.Drawable
4 | import android.graphics.drawable.GradientDrawable
5 | import android.graphics.drawable.RippleDrawable
6 | import android.graphics.drawable.RotateDrawable
7 | import android.os.Build
8 | import java.lang.reflect.Field
9 | import java.lang.reflect.Method
10 |
11 | private val gradientState = resolveGradientState()
12 |
13 | private fun resolveGradientState(): Class<*> {
14 | val classes = GradientDrawable::class.java.declaredClasses
15 | for (singleClass in classes) {
16 | if (singleClass.simpleName == "GradientState") return singleClass
17 | }
18 | throw RuntimeException("GradientState could not be found in current GradientDrawable implementation")
19 | }
20 |
21 | private val rotateState = resolveRotateState()
22 |
23 | private fun resolveRotateState(): Class<*> {
24 | val classes = RotateDrawable::class.java.declaredClasses
25 | for (singleClass in classes) {
26 | if (singleClass.simpleName == "RotateState") return singleClass
27 | }
28 | throw RuntimeException("RotateState could not be found in current RotateDrawable implementation")
29 | }
30 |
31 | @Throws(SecurityException::class, NoSuchFieldException::class)
32 | private fun resolveField(source: Class<*>, fieldName: String): Field {
33 | val field = source.getDeclaredField(fieldName)
34 | field.isAccessible = true
35 | return field
36 | }
37 |
38 | @Throws(SecurityException::class, NoSuchMethodException::class)
39 | private fun resolveMethod(source: Class<*>, methodName: String, vararg parameterTypes: Class<*>): Method {
40 | val method = source.getDeclaredMethod(methodName, *parameterTypes)
41 | method.isAccessible = true
42 | return method
43 | }
44 |
45 | fun setInnerRadius(drawable: GradientDrawable, value: Int) {
46 | try {
47 | val innerRadius = resolveField(gradientState, "mInnerRadius")
48 | innerRadius.setInt(drawable.constantState, value)
49 | } catch (e: NoSuchFieldException) {
50 | e.printStackTrace()
51 | } catch (e: IllegalAccessException) {
52 | e.printStackTrace()
53 | }
54 | }
55 |
56 | fun setInnerRadiusRatio(drawable: GradientDrawable, value: Float) {
57 | try {
58 | val innerRadius = resolveField(gradientState, "mInnerRadiusRatio")
59 | innerRadius.setFloat(drawable.constantState, value)
60 | } catch (e: NoSuchFieldException) {
61 | e.printStackTrace()
62 | } catch (e: IllegalAccessException) {
63 | e.printStackTrace()
64 | }
65 | }
66 |
67 | fun setThickness(drawable: GradientDrawable, value: Int) {
68 | try {
69 | val innerRadius = resolveField(gradientState, "mThickness")
70 | innerRadius.setInt(drawable.constantState, value)
71 | } catch (e: NoSuchFieldException) {
72 | e.printStackTrace()
73 | } catch (e: IllegalAccessException) {
74 | e.printStackTrace()
75 | }
76 | }
77 |
78 | fun setThicknessRatio(drawable: GradientDrawable, value: Float) {
79 | try {
80 | val innerRadius = resolveField(gradientState, "mThicknessRatio")
81 | innerRadius.setFloat(drawable.constantState, value)
82 | } catch (e: NoSuchFieldException) {
83 | e.printStackTrace()
84 | } catch (e: IllegalAccessException) {
85 | e.printStackTrace()
86 | }
87 | }
88 |
89 | fun setUseLevelForShape(drawable: GradientDrawable, value: Boolean) {
90 | try {
91 | val useLevelForShape = resolveField(gradientState, "mUseLevelForShape")
92 | useLevelForShape.setBoolean(drawable.constantState, value)
93 | } catch (e: NoSuchFieldException) {
94 | e.printStackTrace()
95 | } catch (e: IllegalAccessException) {
96 | e.printStackTrace()
97 | }
98 | }
99 |
100 | fun setOrientation(drawable: GradientDrawable, value: GradientDrawable.Orientation) {
101 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
102 | drawable.orientation = value
103 | } else {
104 | try {
105 | val orientation = resolveField(gradientState, "mOrientation")
106 | orientation.set(drawable.constantState, value)
107 | val rectIdDirty = resolveField(GradientDrawable::class.java, "mRectIsDirty")
108 | rectIdDirty.setBoolean(drawable, true)
109 | drawable.invalidateSelf()
110 | } catch (e: NoSuchFieldException) {
111 | e.printStackTrace()
112 | } catch (e: IllegalAccessException) {
113 | e.printStackTrace()
114 | }
115 | }
116 | }
117 |
118 | fun setColors(drawable: GradientDrawable, value: IntArray) {
119 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
120 | drawable.colors = value
121 | } else {
122 | try {
123 | val colors = resolveField(gradientState, "mColors")
124 | colors.set(drawable.constantState, value)
125 | drawable.invalidateSelf()
126 | } catch (e: NoSuchFieldException) {
127 | e.printStackTrace()
128 | } catch (e: IllegalAccessException) {
129 | e.printStackTrace()
130 | }
131 | }
132 | }
133 |
134 | fun setGradientRadiusType(drawable: GradientDrawable, value: Int) {
135 | try {
136 | val type = resolveField(gradientState, "mGradientRadiusType")
137 | type.setInt(drawable.constantState, value)
138 | } catch (e: NoSuchFieldException) {
139 | e.printStackTrace()
140 | } catch (e: IllegalAccessException) {
141 | e.printStackTrace()
142 | }
143 | }
144 |
145 | fun setGradientRadius(drawable: GradientDrawable, value: Float) {
146 | try {
147 | val gradientRadius = resolveField(gradientState, "mGradientRadius")
148 | gradientRadius.setFloat(drawable.constantState, value)
149 | } catch (e: NoSuchFieldException) {
150 | e.printStackTrace()
151 | } catch (e: IllegalAccessException) {
152 | e.printStackTrace()
153 | }
154 | }
155 |
156 | fun setStrokeColor(drawable: GradientDrawable, value: Int) {
157 | try {
158 | val type = resolveField(gradientState, "mStrokeColor")
159 | type.setInt(drawable.constantState, value)
160 | } catch (e: NoSuchFieldException) {
161 | e.printStackTrace()
162 | } catch (e: IllegalAccessException) {
163 | e.printStackTrace()
164 | }
165 | }
166 |
167 | fun setDrawable(rotateDrawable: RotateDrawable, drawable: Drawable) {
168 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
169 | rotateDrawable.drawable = drawable
170 | } else {
171 | try {
172 | val drawableField = resolveField(rotateState, "mDrawable")
173 | val stateField = resolveField(RotateDrawable::class.java, "mState")
174 | drawableField.set(stateField.get(rotateDrawable), drawable)
175 | drawable.callback = rotateDrawable
176 | } catch (e: NoSuchFieldException) {
177 | e.printStackTrace()
178 | } catch (e: IllegalAccessException) {
179 | e.printStackTrace()
180 | }
181 | }
182 | }
183 |
184 | fun setPivotX(rotateDrawable: RotateDrawable, value: Float) {
185 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
186 | rotateDrawable.pivotX = value
187 | } else {
188 | try {
189 | val pivotXField = resolveField(rotateState, "mPivotX")
190 | pivotXField.setFloat(rotateDrawable.constantState, value)
191 | val pivotXRelField = resolveField(rotateState, "mPivotXRel")
192 | pivotXRelField.setBoolean(rotateDrawable.constantState, true)
193 | } catch (e: NoSuchFieldException) {
194 | e.printStackTrace()
195 | } catch (e: IllegalAccessException) {
196 | e.printStackTrace()
197 | }
198 | }
199 | }
200 |
201 | fun setPivotY(rotateDrawable: RotateDrawable, value: Float) {
202 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
203 | rotateDrawable.pivotY = value
204 | } else {
205 | try {
206 | val pivotYField = resolveField(rotateState, "mPivotY")
207 | pivotYField.setFloat(rotateDrawable.constantState, value)
208 | val pivotYRelField = resolveField(rotateState, "mPivotYRel")
209 | pivotYRelField.setBoolean(rotateDrawable.constantState, true)
210 | } catch (e: NoSuchFieldException) {
211 | e.printStackTrace()
212 | } catch (e: IllegalAccessException) {
213 | e.printStackTrace()
214 | }
215 | }
216 | }
217 |
218 | fun setFromDegrees(rotateDrawable: RotateDrawable, value: Float) {
219 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
220 | rotateDrawable.fromDegrees = value
221 | } else {
222 | try {
223 | val fromDegreesField = resolveField(rotateState, "mFromDegrees")
224 | fromDegreesField.setFloat(rotateDrawable.constantState, value)
225 | } catch (e: NoSuchFieldException) {
226 | e.printStackTrace()
227 | } catch (e: IllegalAccessException) {
228 | e.printStackTrace()
229 | }
230 | }
231 | }
232 |
233 | fun setToDegrees(rotateDrawable: RotateDrawable, value: Float) {
234 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
235 | rotateDrawable.toDegrees = value
236 | } else {
237 | try {
238 | val toDegreesField = resolveField(rotateState, "mToDegrees")
239 | toDegreesField.setFloat(rotateDrawable.constantState, value)
240 | } catch (e: NoSuchFieldException) {
241 | e.printStackTrace()
242 | } catch (e: IllegalAccessException) {
243 | e.printStackTrace()
244 | }
245 | }
246 | }
247 |
248 | fun setRadius(rippleDrawable: RippleDrawable, value: Int) {
249 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
250 | rippleDrawable.radius = value
251 | } else {
252 | try {
253 | val setRadiusMethod = resolveMethod(RippleDrawable::class.java, "setMaxRadius", Int::class.java)
254 | setRadiusMethod.invoke(rippleDrawable, value)
255 | } catch (e: NoSuchFieldException) {
256 | e.printStackTrace()
257 | } catch (e: IllegalAccessException) {
258 | e.printStackTrace()
259 | }
260 | }
261 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DrawableToolbox
2 | [](https://github.com/duanhong169/DrawableToolbox/releases)
3 | [](https://developer.android.com/index.html)
4 |
5 | [](https://github.com/duanhong169/DrawableToolbox/blob/master/LICENSE)
6 | [](https://github.com/KotlinBy/awesome-kotlin)
7 |
8 | English | [中文](README_cn.md)
9 |
10 | The missing DrawableToolbox for Android. Create drawables programmatically and get rid of the boring and always repeated `drawable.xml` files.
11 |
12 |
13 |
14 |
15 | ## Features
16 |
17 | * Create drawables programmatically
18 | * Support ``, ``, ``, ``, `` drawables
19 | * Support 'flip' (vertical or horizontal)
20 |
21 | ## Contribute
22 |
23 | * Please file an [issue](https://github.com/duanhong169/DrawableToolbox/issues) or [pull request](https://github.com/duanhong169/DrawableToolbox/pulls)
24 |
25 | ## Gradle
26 |
27 | ```
28 | dependencies {
29 | implementation 'com.github.duanhong169:drawabletoolbox:${latestVersion}'
30 | ...
31 | }
32 | ```
33 |
34 | > Replace `${latestVersion}` with the latest version code. See [releases](https://github.com/duanhong169/DrawableToolbox/releases).
35 |
36 | ## Usage
37 |
38 | Use the `DrawableBuilder` to setup the `Drawable` and call `build()` to create it.
39 |
40 | > Please check all the supported APIs in [DrawableBuilder.kt](https://github.com/duanhong169/DrawableToolbox/blob/master/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/DrawableBuilder.kt).
41 |
42 | Here are some examples:
43 |
44 | Code:
45 |
46 | ```kotlin
47 | DrawableBuilder()
48 | .rectangle()
49 | .hairlineBordered()
50 | .strokeColor(COLOR_DEFAULT)
51 | .strokeColorPressed(COLOR_PRESSED)
52 | .ripple()
53 | .build()
54 | ```
55 |
56 | Result:
57 |
58 | 
59 |
60 | Code:
61 |
62 | ```kotlin
63 | DrawableBuilder()
64 | .rectangle()
65 | .hairlineBordered()
66 | .mediumDashed()
67 | .strokeColor(COLOR_DEFAULT)
68 | .strokeColorPressed(COLOR_PRESSED)
69 | .ripple()
70 | .build()
71 | ```
72 |
73 | Result:
74 |
75 | 
76 |
77 | Code:
78 |
79 | ```kotlin
80 | DrawableBuilder()
81 | .rectangle()
82 | .rounded()
83 | .solidColor(COLOR_DEFAULT)
84 | .solidColorPressed(COLOR_PRESSED)
85 | .build()
86 | ```
87 |
88 | Result:
89 |
90 | 
91 |
92 | Code:
93 |
94 | ```kotlin
95 | DrawableBuilder()
96 | .rectangle()
97 | .hairlineBordered()
98 | .longDashed()
99 | .rounded()
100 | .strokeColor(COLOR_DEFAULT)
101 | .strokeColorPressed(COLOR_PRESSED)
102 | .ripple()
103 | .build()
104 | ```
105 |
106 | Result:
107 |
108 | 
109 |
110 | Code:
111 |
112 | ```kotlin
113 | DrawableBuilder()
114 | .rectangle()
115 | .rounded()
116 | .gradient()
117 | .linearGradient()
118 | .angle(90)
119 | .startColor(COLOR_DEFAULT)
120 | .endColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
121 | .ripple()
122 | .rippleColor(COLOR_PRESSED)
123 | .build()
124 | ```
125 |
126 | Result:
127 |
128 | 
129 |
130 | Code:
131 |
132 | ```kotlin
133 | val baseBuilder = DrawableBuilder()
134 | .rectangle()
135 | .rounded()
136 | .gradient()
137 | .gradientType(GradientDrawable.LINEAR_GRADIENT)
138 | .angle(90)
139 | val normalState = baseBuilder
140 | .startColor(COLOR_DEFAULT)
141 | .endColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
142 | .build()
143 | val pressedState = baseBuilder
144 | .startColor(COLOR_PRESSED)
145 | .endColor(ContextCompat.getColor(context, R.color.colorAccentDark))
146 | .build()
147 |
148 | StateListDrawableBuilder()
149 | .normal(normalState)
150 | .pressed(pressedState)
151 | .build()
152 | ```
153 |
154 | Result:
155 |
156 | 
157 |
158 | Code:
159 |
160 | ```kotlin
161 | val baseBuilder = DrawableBuilder()
162 | .rectangle()
163 | .rounded()
164 | .hairlineBordered()
165 | .strokeColor(COLOR_DEFAULT)
166 | .solidColorSelected(COLOR_DEFAULT)
167 | .ripple()
168 |
169 | return when(type) {
170 | SegmentedControlDrawableSpec.TYPE_LEFT_MOST -> {
171 | baseBuilder.topRightRadius(0)
172 | .bottomRightRadius(0)
173 | .build()
174 | }
175 | SegmentedControlDrawableSpec.TYPE_RIGHT_MOST -> {
176 | baseBuilder.topLeftRadius(0)
177 | .bottomLeftRadius(0)
178 | .build()
179 | }
180 | else -> {
181 | baseBuilder.cornerRadius(0).build()
182 | }
183 | }
184 | ```
185 |
186 | Result:
187 |
188 | 
189 |
190 | Code:
191 |
192 | ```kotlin
193 | val layer1 = DrawableBuilder()
194 | .size(200)
195 | .rectangle()
196 | .rounded()
197 | .hairlineBordered()
198 | .strokeColor(COLOR_DEFAULT)
199 | .strokeColorPressed(COLOR_PRESSED)
200 | .build()
201 | val layer2 = DrawableBuilder()
202 | .rectangle()
203 | .rounded()
204 | .solidColor(COLOR_DEFAULT)
205 | .build()
206 | val layer3 = DrawableBuilder()
207 | .rectangle()
208 | .rounded()
209 | .solidColor(Color.WHITE)
210 | .ripple()
211 | .rippleColor(COLOR_DEFAULT)
212 | .build()
213 | LayerDrawableBuilder()
214 | .add(layer1)
215 | .add(layer2)
216 | .inset(10)
217 | .add(layer3)
218 | .inset(20)
219 | .build()
220 | ```
221 |
222 | Result:
223 |
224 | 
225 |
226 | Code:
227 |
228 | ```kotlin
229 | val layer1 = DrawableBuilder()
230 | .size(180)
231 | .rectangle()
232 | .build()
233 | val layer2 = DrawableBuilder()
234 | .oval()
235 | .solidColor(COLOR_DEFAULT)
236 | .build()
237 | val layer3 = DrawableBuilder()
238 | .rectangle()
239 | .solidColor(COLOR_DEFAULT_DARK)
240 | .rotate(45f)
241 | .build()
242 | val layer4 = DrawableBuilder()
243 | .rectangle()
244 | .bottomLeftRadius(100)
245 | .solidColor(COLOR_DEFAULT_DARK)
246 | .build()
247 | val layer5 = DrawableBuilder()
248 | .oval()
249 | .solidColor(COLOR_DEFAULT)
250 | .build()
251 | val layerDrawable = LayerDrawableBuilder()
252 | .add(layer1)
253 | .add(layer2)
254 | .inset(20, 20, 100, 100)
255 | .add(layer3)
256 | .inset(100, 20, 20, 100)
257 | .add(layer4)
258 | .inset(20, 100, 100, 20)
259 | .add(layer5)
260 | .inset(100, 100, 20, 20)
261 | .build()
262 | DrawableBuilder()
263 | .baseDrawable(layerDrawable)
264 | .rotate(0f, 360f)
265 | .build()
266 | ```
267 |
268 | Result:
269 |
270 | 
271 |
272 |
273 | Code:
274 |
275 | ```kotlin
276 | // Rotate & Leveled the Ring
277 | DrawableBuilder()
278 | .size(200)
279 | .ring()
280 | .useLevelForRing()
281 | .solidColor(COLOR_DEFAULT)
282 | .innerRadiusRatio(3f)
283 | .thicknessRatio(10f)
284 | .rotate(0f, 720f)
285 | .build()
286 | ```
287 |
288 | Result:
289 |
290 | 
291 |
292 | Code:
293 |
294 | ```kotlin
295 | // Rotate, Sweep & Flip the Ring
296 | DrawableBuilder()
297 | .size(200)
298 | .ring()
299 | .innerRadiusRatio(3f)
300 | .thicknessRatio(10f)
301 | .gradient()
302 | .sweepGradient()
303 | .rotate(0f, 360f)
304 | .flip()
305 | .build()
306 | ```
307 |
308 | Result:
309 |
310 | 
311 |
312 | Code:
313 |
314 | ```kotlin
315 | // Rotate, Sweep & Scale the Oval with States
316 | val baseBuilder = DrawableBuilder()
317 | .size(400)
318 | .oval()
319 | .gradient()
320 | .sweepGradient()
321 | .rotate(0f, 360f)
322 | .scale(0.5f)
323 | .scaleGravity(Gravity.START or Gravity.TOP)
324 | val normalState = baseBuilder.build()
325 | val pressedState = baseBuilder
326 | .startColor(COLOR_PRESSED)
327 | .endColor(0x7FFFFFFF)
328 | .build()
329 | StateListDrawableBuilder()
330 | .normal(normalState)
331 | .pressed(pressedState)
332 | .build()
333 | ```
334 |
335 | Result:
336 |
337 | 
338 |
339 | Please check out the app sample code [SampleCodeSnippets.kt](https://github.com/duanhong169/DrawableToolbox/blob/master/app/src/main/java/top/defaults/drawabletoolboxapp/SampleCodeSnippets.kt) for more details.
340 |
341 | ## License
342 |
343 | Copyright 2018 Hong Duan
344 |
345 | Licensed under the Apache License, Version 2.0 (the "License");
346 | you may not use this file except in compliance with the License.
347 | You may obtain a copy of the License at
348 |
349 | http://www.apache.org/licenses/LICENSE-2.0
350 |
351 | Unless required by applicable law or agreed to in writing, software
352 | distributed under the License is distributed on an "AS IS" BASIS,
353 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
354 | See the License for the specific language governing permissions and
355 | limitations under the License.
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/DrawableProperties.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.content.res.ColorStateList
4 | import android.graphics.Color
5 | import android.graphics.drawable.Drawable
6 | import android.graphics.drawable.GradientDrawable
7 | import android.os.Parcel
8 | import android.os.Parcelable
9 | import android.view.Gravity
10 |
11 | data class DrawableProperties (
12 |
13 | //
14 | @JvmField var shape: Int = GradientDrawable.RECTANGLE,
15 | @JvmField var innerRadius: Int = -1,
16 | @JvmField var innerRadiusRatio: Float = 9f,
17 | @JvmField var thickness: Int = -1,
18 | @JvmField var thicknessRatio: Float = 3f,
19 | @JvmField var useLevelForRing: Boolean = false,
20 |
21 | //
22 | private var _cornerRadius: Int = 0,
23 | @JvmField var topLeftRadius: Int = 0,
24 | @JvmField var topRightRadius: Int = 0,
25 | @JvmField var bottomRightRadius: Int = 0,
26 | @JvmField var bottomLeftRadius: Int = 0,
27 |
28 | //
29 | @JvmField var useGradient: Boolean = false,
30 | @JvmField var type: Int = GradientDrawable.RADIAL_GRADIENT,
31 | @JvmField var angle: Int = 0,
32 | @JvmField var centerX: Float = 0.5f,
33 | @JvmField var centerY: Float = 0.5f,
34 | @JvmField var useCenterColor: Boolean = false,
35 | @JvmField var startColor: Int = Constants.DEFAULT_COLOR,
36 | @JvmField var centerColor: Int? = null,
37 | @JvmField var endColor: Int = 0x7FFFFFFF,
38 | @JvmField var gradientRadiusType: Int = RADIUS_TYPE_FRACTION,
39 | @JvmField var gradientRadius: Float = 0.5f,
40 | @JvmField var useLevelForGradient: Boolean = false,
41 |
42 | //
43 | @JvmField var width: Int = -1,
44 | @JvmField var height: Int = -1,
45 |
46 | //
47 | @JvmField var solidColor: Int = Color.TRANSPARENT,
48 | @JvmField var solidColorStateList: ColorStateList? = null,
49 |
50 | //
51 | @JvmField var strokeWidth: Int = 0,
52 | @JvmField var strokeColor: Int = Color.DKGRAY,
53 | @JvmField var strokeColorStateList: ColorStateList? = null,
54 | @JvmField var dashWidth: Int = 0,
55 | @JvmField var dashGap: Int = 0,
56 |
57 | //
58 | @JvmField var useRotate: Boolean = false,
59 | @JvmField var pivotX: Float = 0.5f,
60 | @JvmField var pivotY: Float = 0.5f,
61 | @JvmField var fromDegrees: Float = 0f,
62 | @JvmField var toDegrees: Float = 0f,
63 |
64 | //
65 | @JvmField var useScale: Boolean = false,
66 | @JvmField var scaleLevel: Int = 10000,
67 | @JvmField var scaleGravity: Int = Gravity.CENTER,
68 | @JvmField var scaleWidth: Float = 0f,
69 | @JvmField var scaleHeight: Float = 0f,
70 |
71 | // flip
72 | @JvmField var useFlip: Boolean = false,
73 | @JvmField var orientation: Int = FlipDrawable.ORIENTATION_HORIZONTAL,
74 |
75 | // ripple
76 | @JvmField var useRipple: Boolean = false,
77 | @JvmField var rippleColor: Int = Constants.DEFAULT_COLOR,
78 | @JvmField var rippleColorStateList: ColorStateList? = null,
79 | @JvmField var rippleRadius: Int = -1
80 | ) : Parcelable {
81 |
82 | companion object {
83 | const val RADIUS_TYPE_PIXELS = 0
84 | const val RADIUS_TYPE_FRACTION = 1
85 |
86 | @JvmField val CREATOR = object : Parcelable.Creator {
87 | override fun createFromParcel(parcel: Parcel): DrawableProperties {
88 | return DrawableProperties(parcel)
89 | }
90 |
91 | override fun newArray(size: Int): Array {
92 | return arrayOfNulls(size)
93 | }
94 | }
95 | }
96 |
97 | var cornerRadius: Int = _cornerRadius
98 | set(value) {
99 | _cornerRadius = value
100 | topLeftRadius = value
101 | topRightRadius = value
102 | bottomRightRadius = value
103 | bottomLeftRadius = value
104 | }
105 |
106 | constructor(parcel: Parcel) : this(
107 | parcel.readInt(),
108 | parcel.readInt(),
109 | parcel.readFloat(),
110 | parcel.readInt(),
111 | parcel.readFloat(),
112 | parcel.readByte() != 0.toByte(),
113 | parcel.readInt(),
114 | parcel.readInt(),
115 | parcel.readInt(),
116 | parcel.readInt(),
117 | parcel.readInt(),
118 | parcel.readByte() != 0.toByte(),
119 | parcel.readInt(),
120 | parcel.readInt(),
121 | parcel.readFloat(),
122 | parcel.readFloat(),
123 | parcel.readByte() != 0.toByte(),
124 | parcel.readInt(),
125 | parcel.readValue(Int::class.java.classLoader) as? Int,
126 | parcel.readInt(),
127 | parcel.readInt(),
128 | parcel.readFloat(),
129 | parcel.readByte() != 0.toByte(),
130 | parcel.readInt(),
131 | parcel.readInt(),
132 | parcel.readInt(),
133 | parcel.readParcelable(ColorStateList::class.java.classLoader),
134 | parcel.readInt(),
135 | parcel.readInt(),
136 | parcel.readParcelable(ColorStateList::class.java.classLoader),
137 | parcel.readInt(),
138 | parcel.readInt(),
139 | parcel.readByte() != 0.toByte(),
140 | parcel.readFloat(),
141 | parcel.readFloat(),
142 | parcel.readFloat(),
143 | parcel.readFloat(),
144 | parcel.readByte() != 0.toByte(),
145 | parcel.readInt(),
146 | parcel.readInt(),
147 | parcel.readFloat(),
148 | parcel.readFloat(),
149 | parcel.readByte() != 0.toByte(),
150 | parcel.readInt(),
151 | parcel.readByte() != 0.toByte(),
152 | parcel.readInt(),
153 | parcel.readParcelable(ColorStateList::class.java.classLoader),
154 | parcel.readInt()) {
155 | }
156 |
157 | fun copy(): DrawableProperties {
158 | val parcel = Parcel.obtain()
159 | writeToParcel(parcel, 0)
160 | parcel.setDataPosition(0)
161 | val properties = DrawableProperties.CREATOR.createFromParcel(parcel)
162 | parcel.recycle()
163 | return properties
164 | }
165 |
166 | fun getCornerRadii(): FloatArray {
167 | return floatArrayOf(topLeftRadius.toFloat(), topLeftRadius.toFloat(),
168 | topRightRadius.toFloat(), topRightRadius.toFloat(),
169 | bottomRightRadius.toFloat(), bottomRightRadius.toFloat(),
170 | bottomLeftRadius.toFloat(), bottomLeftRadius.toFloat())
171 | }
172 |
173 | fun getOrientation(): GradientDrawable.Orientation {
174 | val angle = this.angle % 360
175 | val orientation: GradientDrawable.Orientation
176 | orientation = when (angle) {
177 | 0 -> GradientDrawable.Orientation.LEFT_RIGHT
178 | 45 -> GradientDrawable.Orientation.BL_TR
179 | 90 -> GradientDrawable.Orientation.BOTTOM_TOP
180 | 135 -> GradientDrawable.Orientation.BR_TL
181 | 180 -> GradientDrawable.Orientation.RIGHT_LEFT
182 | 225 -> GradientDrawable.Orientation.TR_BL
183 | 270 -> GradientDrawable.Orientation.TOP_BOTTOM
184 | 315 -> GradientDrawable.Orientation.TL_BR
185 | else -> throw IllegalArgumentException("Unsupported angle: $angle")
186 | }
187 | return orientation
188 | }
189 |
190 | fun getColors(): IntArray {
191 | return if (useCenterColor && centerColor != null) {
192 | intArrayOf(startColor, centerColor!!, endColor)
193 | } else intArrayOf(startColor, endColor)
194 | }
195 |
196 | fun materialization(): Drawable = DrawableBuilder().batch(this).build()
197 |
198 | override fun writeToParcel(parcel: Parcel, flags: Int) {
199 | parcel.writeInt(shape)
200 | parcel.writeInt(innerRadius)
201 | parcel.writeFloat(innerRadiusRatio)
202 | parcel.writeInt(thickness)
203 | parcel.writeFloat(thicknessRatio)
204 | parcel.writeByte(if (useLevelForRing) 1 else 0)
205 | parcel.writeInt(_cornerRadius)
206 | parcel.writeInt(topLeftRadius)
207 | parcel.writeInt(topRightRadius)
208 | parcel.writeInt(bottomRightRadius)
209 | parcel.writeInt(bottomLeftRadius)
210 | parcel.writeByte(if (useGradient) 1 else 0)
211 | parcel.writeInt(type)
212 | parcel.writeInt(angle)
213 | parcel.writeFloat(centerX)
214 | parcel.writeFloat(centerY)
215 | parcel.writeByte(if (useCenterColor) 1 else 0)
216 | parcel.writeInt(startColor)
217 | parcel.writeValue(centerColor)
218 | parcel.writeInt(endColor)
219 | parcel.writeInt(gradientRadiusType)
220 | parcel.writeFloat(gradientRadius)
221 | parcel.writeByte(if (useLevelForGradient) 1 else 0)
222 | parcel.writeInt(width)
223 | parcel.writeInt(height)
224 | parcel.writeInt(solidColor)
225 | parcel.writeParcelable(solidColorStateList, flags)
226 | parcel.writeInt(strokeWidth)
227 | parcel.writeInt(strokeColor)
228 | parcel.writeParcelable(strokeColorStateList, flags)
229 | parcel.writeInt(dashWidth)
230 | parcel.writeInt(dashGap)
231 | parcel.writeByte(if (useRotate) 1 else 0)
232 | parcel.writeFloat(pivotX)
233 | parcel.writeFloat(pivotY)
234 | parcel.writeFloat(fromDegrees)
235 | parcel.writeFloat(toDegrees)
236 | parcel.writeByte(if (useScale) 1 else 0)
237 | parcel.writeInt(scaleLevel)
238 | parcel.writeInt(scaleGravity)
239 | parcel.writeFloat(scaleWidth)
240 | parcel.writeFloat(scaleHeight)
241 | parcel.writeByte(if (useFlip) 1 else 0)
242 | parcel.writeInt(orientation)
243 | parcel.writeByte(if (useRipple) 1 else 0)
244 | parcel.writeInt(rippleColor)
245 | parcel.writeParcelable(rippleColorStateList, flags)
246 | parcel.writeInt(rippleRadius)
247 | }
248 |
249 | override fun describeContents(): Int {
250 | return 0
251 | }
252 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2018 Hong Duan
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/app/src/main/java/top/defaults/drawabletoolboxapp/SampleCodeSnippets.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolboxapp
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.graphics.Path
6 | import android.graphics.drawable.Drawable
7 | import android.graphics.drawable.GradientDrawable
8 | import android.support.v4.content.ContextCompat
9 | import android.view.Gravity
10 | import top.defaults.drawabletoolbox.DrawableBuilder
11 | import top.defaults.drawabletoolbox.LayerDrawableBuilder
12 | import top.defaults.drawabletoolbox.PathShapeDrawableBuilder
13 | import top.defaults.drawabletoolbox.StateListDrawableBuilder
14 | import top.defaults.drawabletoolboxapp.spec.DrawableSpec
15 | import top.defaults.drawabletoolboxapp.spec.ImageViewSourceDrawableSpec
16 | import top.defaults.drawabletoolboxapp.spec.SegmentedControlDrawableSpec
17 | import top.defaults.drawabletoolboxapp.spec.TextViewBackgroundDrawableSpec
18 |
19 | const val COLOR_DEFAULT = 0xFFBA68C8.toInt()
20 | const val COLOR_DEFAULT_DARK = 0xFF9C27B0.toInt()
21 | const val COLOR_PRESSED = 0xFFF44336.toInt()
22 |
23 | fun samples(context: Context): List {
24 | return listOf(
25 | TextViewBackgroundDrawableSpec("Bordered with Ripple", object : DrawableFactory {
26 | override fun build(): Drawable {
27 | return DrawableBuilder()
28 | .rectangle()
29 | .hairlineBordered()
30 | .strokeColor(COLOR_DEFAULT)
31 | .strokeColorPressed(COLOR_PRESSED)
32 | .ripple()
33 | .build()
34 | }
35 | }),
36 | TextViewBackgroundDrawableSpec("Medium-dashed, Bordered with Ripple", object : DrawableFactory {
37 | override fun build(): Drawable {
38 | return DrawableBuilder()
39 | .rectangle()
40 | .hairlineBordered()
41 | .mediumDashed()
42 | .strokeColor(COLOR_DEFAULT)
43 | .strokeColorPressed(COLOR_PRESSED)
44 | .ripple()
45 | .build()
46 | }
47 | }),
48 | TextViewBackgroundDrawableSpec("Filled with States", object : DrawableFactory {
49 | override fun build(): Drawable {
50 | return DrawableBuilder()
51 | .rectangle()
52 | .solidColor(COLOR_DEFAULT)
53 | .solidColorPressed(COLOR_PRESSED)
54 | .build()
55 | }
56 | }).isDarkBackground(),
57 | TextViewBackgroundDrawableSpec("Rounded, Filled with States", object : DrawableFactory {
58 | override fun build(): Drawable {
59 | return DrawableBuilder()
60 | .rectangle()
61 | .rounded()
62 | .solidColor(COLOR_DEFAULT)
63 | .solidColorPressed(COLOR_PRESSED)
64 | .build()
65 | }
66 | }).isDarkBackground(),
67 | TextViewBackgroundDrawableSpec("Rounded, Bordered with Ripple", object : DrawableFactory {
68 | override fun build(): Drawable {
69 | return DrawableBuilder()
70 | .rectangle()
71 | .hairlineBordered()
72 | .rounded()
73 | .strokeColor(COLOR_DEFAULT)
74 | .strokeColorPressed(COLOR_PRESSED)
75 | .ripple()
76 | .build()
77 | }
78 | }),
79 | TextViewBackgroundDrawableSpec("Rounded, Long-dashed, Bordered with Ripple", object : DrawableFactory {
80 | override fun build(): Drawable {
81 | return DrawableBuilder()
82 | .rectangle()
83 | .hairlineBordered()
84 | .longDashed()
85 | .rounded()
86 | .strokeColor(COLOR_DEFAULT)
87 | .strokeColorPressed(COLOR_PRESSED)
88 | .ripple()
89 | .build()
90 | }
91 | }),
92 | TextViewBackgroundDrawableSpec("Rounded, Filled with Ripple", object : DrawableFactory {
93 | override fun build(): Drawable {
94 | return DrawableBuilder()
95 | .rectangle()
96 | .rounded()
97 | .solidColor(COLOR_DEFAULT)
98 | .ripple()
99 | .rippleColor(COLOR_PRESSED)
100 | .build()
101 | }
102 | }).isDarkBackground(),
103 | TextViewBackgroundDrawableSpec("Rounded, Gradient with Ripple", object : DrawableFactory {
104 | override fun build(): Drawable {
105 | return DrawableBuilder()
106 | .rectangle()
107 | .rounded()
108 | .gradient()
109 | .linearGradient()
110 | .angle(90)
111 | .startColor(COLOR_DEFAULT)
112 | .endColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
113 | .ripple()
114 | .rippleColor(COLOR_PRESSED)
115 | .build()
116 | }
117 | }).isDarkBackground(),
118 | TextViewBackgroundDrawableSpec("Rounded, Gradient with States", object : DrawableFactory {
119 | override fun build(): Drawable {
120 | val baseBuilder = DrawableBuilder()
121 | .rectangle()
122 | .rounded()
123 | .gradient()
124 | .gradientType(GradientDrawable.LINEAR_GRADIENT)
125 | .angle(90)
126 | val normalState = baseBuilder
127 | .startColor(COLOR_DEFAULT)
128 | .endColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
129 | .build()
130 | val pressedState = baseBuilder
131 | .startColor(COLOR_PRESSED)
132 | .endColor(ContextCompat.getColor(context, R.color.colorAccentDark))
133 | .build()
134 | return StateListDrawableBuilder()
135 | .normal(normalState)
136 | .pressed(pressedState)
137 | .build()
138 | }
139 | }).isDarkBackground(),
140 | SegmentedControlDrawableSpec("Segmented Control", object : DrawableFactory {
141 |
142 | override fun build(): Drawable = throw RuntimeException("Unsupported build with no index")
143 |
144 | override fun build(drawableSpec: DrawableSpec, index: Int): Drawable {
145 | if (drawableSpec is SegmentedControlDrawableSpec) {
146 | val type = drawableSpec.getType(index)
147 |
148 | val baseBuilder = DrawableBuilder()
149 | .rectangle()
150 | .rounded()
151 | .hairlineBordered()
152 | .strokeColor(COLOR_DEFAULT)
153 | .solidColorSelected(COLOR_DEFAULT)
154 | .ripple()
155 |
156 | return when(type) {
157 | SegmentedControlDrawableSpec.TYPE_LEFT_MOST -> {
158 | baseBuilder.topRightRadius(0)
159 | .bottomRightRadius(0)
160 | .build()
161 | }
162 | SegmentedControlDrawableSpec.TYPE_RIGHT_MOST -> {
163 | baseBuilder.topLeftRadius(0)
164 | .bottomLeftRadius(0)
165 | .build()
166 | }
167 | else -> {
168 | baseBuilder.cornerRadius(0).build()
169 | }
170 | }
171 | } else {
172 | throw RuntimeException("Unsupported drawableSpec")
173 | }
174 | }
175 |
176 | }),
177 | TextViewBackgroundDrawableSpec("Layer List: Several Borders", object : DrawableFactory {
178 | override fun build(): Drawable {
179 | val layer1 = DrawableBuilder()
180 | .size(200)
181 | .rectangle()
182 | .rounded()
183 | .hairlineBordered()
184 | .strokeColor(COLOR_DEFAULT)
185 | .strokeColorPressed(COLOR_PRESSED)
186 | .build()
187 | val layer2 = DrawableBuilder()
188 | .rectangle()
189 | .rounded()
190 | .solidColor(COLOR_DEFAULT)
191 | .build()
192 | val layer3 = DrawableBuilder()
193 | .rectangle()
194 | .rounded()
195 | .solidColor(Color.WHITE)
196 | .ripple()
197 | .rippleColor(COLOR_DEFAULT)
198 | .build()
199 | return LayerDrawableBuilder()
200 | .add(layer1)
201 | .add(layer2)
202 | .inset(10)
203 | .add(layer3)
204 | .inset(20)
205 | .build()
206 | }
207 | }),
208 | ImageViewSourceDrawableSpec("Showcase: Layer List 1", object : DrawableFactory {
209 | override fun build(): Drawable {
210 | val layer1 = DrawableBuilder()
211 | .size(180)
212 | .rectangle()
213 | .build()
214 | val layer2 = DrawableBuilder()
215 | .oval()
216 | .solidColor(COLOR_DEFAULT)
217 | .build()
218 | val layer3 = DrawableBuilder()
219 | .rectangle()
220 | .solidColor(COLOR_DEFAULT_DARK)
221 | .rotate(45f)
222 | .build()
223 | val layer4 = DrawableBuilder()
224 | .rectangle()
225 | .bottomLeftRadius(100)
226 | .solidColor(COLOR_DEFAULT_DARK)
227 | .build()
228 | val layer5 = DrawableBuilder()
229 | .oval()
230 | .solidColor(COLOR_DEFAULT)
231 | .build()
232 | val layerDrawable = LayerDrawableBuilder()
233 | .add(layer1)
234 | .add(layer2)
235 | .inset(20, 20, 100, 100)
236 | .add(layer3)
237 | .inset(100, 20, 20, 100)
238 | .add(layer4)
239 | .inset(20, 100, 100, 20)
240 | .add(layer5)
241 | .inset(100, 100, 20, 20)
242 | .build()
243 | return DrawableBuilder()
244 | .baseDrawable(layerDrawable)
245 | .rotate(0f, 360f)
246 | .build()
247 | }
248 | }).animateRestart().initialLevel(8750),
249 | ImageViewSourceDrawableSpec("Rotate & Leveled the Ring", object : DrawableFactory {
250 | override fun build(): Drawable {
251 | return DrawableBuilder()
252 | .size(200)
253 | .ring()
254 | .useLevelForRing()
255 | .solidColor(COLOR_DEFAULT)
256 | .innerRadiusRatio(3f)
257 | .thicknessRatio(10f)
258 | .rotate(0f, 720f)
259 | .build()
260 | }
261 | }).animateReverse().initialLevel(5000),
262 | ImageViewSourceDrawableSpec("Star", object : DrawableFactory {
263 | fun star(): Path {
264 | val path = Path()
265 | val half = 50
266 | path.moveTo(half * 0.5f, half * 0.84f)
267 | path.lineTo(half * 1.5f, half * 0.84f)
268 | path.lineTo(half * 0.68f, half * 1.45f)
269 | path.lineTo(half * 1.0f, half * 0.5f)
270 | path.lineTo(half * 1.32f, half * 1.45f)
271 | path.lineTo(half * 0.5f, half * 0.84f)
272 | path.close()
273 | return path
274 | }
275 |
276 | override fun build(): Drawable {
277 | return PathShapeDrawableBuilder()
278 | .path(star(), 100f, 100f)
279 | .size(200)
280 | .build {
281 | it.paint.color = COLOR_DEFAULT
282 | }
283 | }
284 | }),
285 | ImageViewSourceDrawableSpec("Rotate & Sweep the Ring", object : DrawableFactory {
286 | override fun build(): Drawable {
287 | return DrawableBuilder()
288 | .size(200)
289 | .ring()
290 | .innerRadiusRatio(3f)
291 | .thicknessRatio(10f)
292 | .gradient()
293 | .sweepGradient()
294 | .rotate(0f, 360f)
295 | .build()
296 | }
297 | }).animateRestart(),
298 | ImageViewSourceDrawableSpec("Rotate, Sweep & Flip the Ring", object : DrawableFactory {
299 | override fun build(): Drawable {
300 | return DrawableBuilder()
301 | .size(200)
302 | .ring()
303 | .innerRadiusRatio(3f)
304 | .thicknessRatio(10f)
305 | .gradient()
306 | .sweepGradient()
307 | .rotate(0f, 360f)
308 | .flip()
309 | .build()
310 | }
311 | }).animateRestart(),
312 | ImageViewSourceDrawableSpec("Rotate, Sweep & Scale the Oval with States", object : DrawableFactory {
313 | override fun build(): Drawable {
314 | val baseBuilder = DrawableBuilder()
315 | .size(400)
316 | .oval()
317 | .gradient()
318 | .sweepGradient()
319 | .rotate(0f, 360f)
320 | .scale(0.5f)
321 | .scaleGravity(Gravity.START or Gravity.TOP)
322 | val normalState = baseBuilder.build()
323 | val pressedState = baseBuilder
324 | .startColor(COLOR_PRESSED)
325 | .endColor(0x7FFFFFFF)
326 | .build()
327 | return StateListDrawableBuilder()
328 | .normal(normalState)
329 | .pressed(pressedState)
330 | .build()
331 | }
332 | }).animateReverse(),
333 | ImageViewSourceDrawableSpec("Oval with States", object : DrawableFactory {
334 | override fun build(): Drawable {
335 | return DrawableBuilder()
336 | .size(200)
337 | .oval()
338 | .solidColor(COLOR_DEFAULT)
339 | .solidColorPressed(COLOR_PRESSED)
340 | .build()
341 | }
342 | }),
343 | ImageViewSourceDrawableSpec("Oval with Radial", object : DrawableFactory {
344 | override fun build(): Drawable {
345 | return DrawableBuilder()
346 | .size(200)
347 | .oval()
348 | .gradient()
349 | .radialGradient()
350 | .build()
351 | }
352 | })
353 | )
354 | }
355 |
--------------------------------------------------------------------------------
/drawabletoolbox/src/main/java/top/defaults/drawabletoolbox/DrawableBuilder.kt:
--------------------------------------------------------------------------------
1 | package top.defaults.drawabletoolbox
2 |
3 | import android.content.res.ColorStateList
4 | import android.graphics.drawable.Drawable
5 | import android.graphics.drawable.GradientDrawable
6 | import android.os.Build
7 | import android.util.StateSet
8 | import java.util.*
9 | import java.util.concurrent.atomic.AtomicInteger
10 |
11 | class DrawableBuilder {
12 |
13 | private var properties = DrawableProperties()
14 | private var order: AtomicInteger = AtomicInteger(1)
15 | private var transformsMap = TreeMap Drawable>()
16 | private var baseDrawable: Drawable? = null
17 |
18 | fun batch(properties: DrawableProperties) = apply { this.properties = properties.copy() }
19 | fun baseDrawable(drawable: Drawable) = apply { baseDrawable = drawable }
20 |
21 | //
22 | fun shape(shape: Int) = apply { properties.shape = shape }
23 | fun rectangle() = apply { shape(GradientDrawable.RECTANGLE) }
24 | fun oval() = apply { shape(GradientDrawable.OVAL) }
25 | fun line() = apply { shape(GradientDrawable.LINE) }
26 | fun ring() = apply { shape(GradientDrawable.RING) }
27 | fun innerRadius(innerRadius: Int) = apply { properties.innerRadius = innerRadius }
28 | fun innerRadiusRatio(innerRadiusRatio: Float) = apply { properties.innerRadiusRatio = innerRadiusRatio }
29 | fun thickness(thickness: Int) = apply { properties.thickness = thickness }
30 | fun thicknessRatio(thicknessRatio: Float) = apply { properties.thicknessRatio = thicknessRatio }
31 | @JvmOverloads fun useLevelForRing(use: Boolean = true) = apply { properties.useLevelForRing = use }
32 |
33 | //
34 | fun cornerRadius(cornerRadius: Int) = apply { properties.cornerRadius = cornerRadius }
35 | fun topLeftRadius(topLeftRadius: Int) = apply { properties.topLeftRadius = topLeftRadius }
36 | fun topRightRadius(topRightRadius: Int) = apply { properties.topRightRadius = topRightRadius }
37 | fun bottomRightRadius(bottomRightRadius: Int) = apply { properties.bottomRightRadius = bottomRightRadius }
38 | fun bottomLeftRadius(bottomLeftRadius: Int) = apply { properties.bottomLeftRadius = bottomLeftRadius }
39 | fun rounded() = apply { cornerRadius(Int.MAX_VALUE) }
40 | fun cornerRadii(topLeftRadius: Int, topRightRadius: Int, bottomRightRadius: Int, bottomLeftRadius: Int) = apply {
41 | topLeftRadius(topLeftRadius); topRightRadius(topRightRadius); bottomRightRadius(bottomRightRadius); bottomLeftRadius(bottomLeftRadius)
42 | }
43 |
44 | //
45 | @JvmOverloads fun gradient(useGradient: Boolean = true) = apply { properties.useGradient = useGradient }
46 | fun gradientType(type: Int) = apply { properties.type = type }
47 | fun linearGradient() = apply { gradientType(GradientDrawable.LINEAR_GRADIENT) }
48 | fun radialGradient() = apply { gradientType(GradientDrawable.RADIAL_GRADIENT) }
49 | fun sweepGradient() = apply { gradientType(GradientDrawable.SWEEP_GRADIENT) }
50 | fun angle(angle: Int) = apply { properties.angle = angle }
51 | fun centerX(centerX: Float) = apply { properties.centerX = centerX }
52 | fun centerY(centerY: Float) = apply { properties.centerY = centerY }
53 | fun center(centerX: Float, centerY: Float) = apply { centerX(centerX); centerY(centerY) }
54 | @JvmOverloads fun useCenterColor(useCenterColor: Boolean = true) = apply { properties.useCenterColor = useCenterColor }
55 | fun startColor(startColor: Int) = apply { properties.startColor = startColor }
56 | fun centerColor(centerColor: Int) = apply {
57 | properties.centerColor = centerColor
58 | useCenterColor(true)
59 | }
60 | fun endColor(endColor: Int) = apply { properties.endColor = endColor }
61 | fun gradientColors(startColor: Int, endColor: Int, centerColor: Int?) = apply {
62 | startColor(startColor); endColor(endColor)
63 | useCenterColor(centerColor != null)
64 | centerColor?.let {
65 | centerColor(it)
66 | }
67 | }
68 | fun gradientRadiusType(gradientRadiusType: Int) = apply { properties.gradientRadiusType = gradientRadiusType }
69 | fun gradientRadius(gradientRadius: Float) = apply { properties.gradientRadius = gradientRadius }
70 | fun gradientRadius(radius: Float, type: Int) = apply { gradientRadius(radius); gradientRadiusType(type) }
71 | fun gradientRadiusInPixel(radius: Float) = apply { gradientRadius(radius); gradientRadiusType(DrawableProperties.RADIUS_TYPE_PIXELS) }
72 | fun gradientRadiusInFraction(radius: Float) = apply { gradientRadius(radius); gradientRadiusType(DrawableProperties.RADIUS_TYPE_FRACTION) }
73 | fun useLevelForGradient(use: Boolean) = apply { properties.useLevelForGradient = use }
74 | fun useLevelForGradient() = apply { useLevelForGradient(true) }
75 |
76 | //
77 | fun width(width: Int) = apply { properties.width = width }
78 | fun height(height: Int) = apply { properties.height = height }
79 | fun size(width: Int, height: Int) = apply { width(width); height(height) }
80 | fun size(size: Int) = apply { width(size).height(size) }
81 |
82 | //
83 | fun solidColor(solidColor: Int) = apply { properties.solidColor = solidColor }
84 | private var solidColorPressed: Int? = null
85 | fun solidColorPressed(color: Int?) = apply { solidColorPressed = color }
86 | private var solidColorPressedWhenRippleUnsupported: Int? = null
87 | fun solidColorPressedWhenRippleUnsupported(color: Int?) = apply { solidColorPressedWhenRippleUnsupported = color }
88 | private var solidColorDisabled: Int? = null
89 | fun solidColorDisabled(color: Int?) = apply { solidColorDisabled = color }
90 | private var solidColorSelected: Int? = null
91 | fun solidColorSelected(color: Int?) = apply { solidColorSelected = color }
92 | fun solidColorStateList(colorStateList: ColorStateList) = apply { properties.solidColorStateList = colorStateList }
93 |
94 | //
95 | fun strokeWidth(strokeWidth: Int) = apply { properties.strokeWidth = strokeWidth }
96 |
97 | fun strokeColor(strokeColor: Int) = apply { properties.strokeColor = strokeColor }
98 | private var strokeColorPressed: Int? = null
99 | fun strokeColorPressed(color: Int?) = apply { strokeColorPressed = color }
100 | private var strokeColorDisabled: Int? = null
101 | fun strokeColorDisabled(color: Int?) = apply { strokeColorDisabled = color }
102 | private var strokeColorSelected: Int? = null
103 | fun strokeColorSelected(color: Int?) = apply { strokeColorSelected = color }
104 | fun strokeColorStateList(colorStateList: ColorStateList) = apply { properties.strokeColorStateList = colorStateList }
105 |
106 | fun dashWidth(dashWidth: Int) = apply { properties.dashWidth = dashWidth }
107 | fun dashGap(dashGap: Int) = apply { properties.dashGap = dashGap }
108 | fun hairlineBordered() = apply { strokeWidth(1) }
109 | fun shortDashed() = apply { dashWidth(12).dashGap(12) }
110 | fun mediumDashed() = apply { dashWidth(24).dashGap(24) }
111 | fun longDashed() = apply { dashWidth(36).dashGap(36) }
112 | fun dashed() = apply { mediumDashed() }
113 |
114 | //
115 | private var rotateOrder = 0
116 | @JvmOverloads fun rotate(boolean: Boolean = true) = apply {
117 | properties.useRotate = boolean
118 | rotateOrder = if (boolean) {
119 | order.getAndIncrement()
120 | } else {
121 | 0
122 | }
123 | }
124 | fun pivotX(pivotX: Float) = apply { properties.pivotX = pivotX }
125 | fun pivotY(pivotY: Float) = apply { properties.pivotY = pivotY }
126 | fun pivot(pivotX: Float, pivotY: Float) = apply { pivotX(pivotX).pivotY(pivotY) }
127 | fun fromDegrees(degrees: Float) = apply { properties.fromDegrees = degrees }
128 | fun toDegrees(degrees: Float) = apply { properties.toDegrees = degrees }
129 | fun degrees(fromDegrees: Float, toDegrees: Float) = apply { fromDegrees(fromDegrees).toDegrees(toDegrees) }
130 | fun degrees(degrees: Float) = apply { fromDegrees(degrees).toDegrees(degrees) }
131 | fun rotate(fromDegrees: Float, toDegrees: Float) = apply { rotate().fromDegrees(fromDegrees).toDegrees(toDegrees) }
132 | fun rotate(degrees: Float) = apply { rotate().degrees(degrees) }
133 |
134 | //
135 | private var scaleOrder = 0
136 | @JvmOverloads fun scale(boolean: Boolean = true) = apply {
137 | properties.useScale = boolean
138 | scaleOrder = if (boolean) {
139 | order.getAndIncrement()
140 | } else {
141 | 0
142 | }
143 | }
144 | fun scaleLevel(level: Int) = apply { properties.scaleLevel = level }
145 | fun scaleGravity(gravity: Int) = apply { properties.scaleGravity = gravity }
146 | fun scaleWidth(scale: Float) = apply { properties.scaleWidth = scale }
147 | fun scaleHeight(scale: Float) = apply { properties.scaleHeight = scale }
148 | fun scale(scale: Float) = apply { scale().scaleWidth(scale).scaleHeight(scale) }
149 | fun scale(scaleWidth: Float, scaleHeight: Float) = apply { scale().scaleWidth(scaleWidth).scaleHeight(scaleHeight) }
150 |
151 | // flip
152 | @JvmOverloads fun flip(boolean: Boolean = true) = apply { properties.useFlip = boolean }
153 | fun orientation(orientation: Int) = apply { properties.orientation = orientation }
154 | fun flipVertical() = apply { flip().orientation(FlipDrawable.ORIENTATION_VERTICAL) }
155 |
156 | //
157 | @JvmOverloads fun ripple(boolean: Boolean = true) = apply { properties.useRipple = boolean }
158 | fun rippleColor(color: Int) = apply { properties.rippleColor = color }
159 | fun rippleColorStateList(colorStateList: ColorStateList) = apply { properties.rippleColorStateList = colorStateList }
160 | fun rippleRadius(radius: Int) = apply { properties.rippleRadius = radius }
161 |
162 | fun build(): Drawable {
163 | if (baseDrawable != null) {
164 | return wrap(baseDrawable!!)
165 | }
166 |
167 | var drawable: Drawable
168 |
169 | // fall back when ripple is unavailable on devices with API < 21
170 | if (shouldFallbackRipple()) {
171 | if (solidColorPressedWhenRippleUnsupported != null) {
172 | solidColorPressed(solidColorPressedWhenRippleUnsupported)
173 | } else {
174 | solidColorPressed(properties.rippleColor)
175 | }
176 | }
177 |
178 | if (needStateListDrawable()) {
179 | drawable = StateListDrawableBuilder()
180 | .pressed(buildPressedDrawable())
181 | .disabled(buildDisabledDrawable())
182 | .selected(buildSelectedDrawable())
183 | .normal(buildNormalDrawable())
184 | .build()
185 | } else {
186 | drawable = GradientDrawable()
187 | setupGradientDrawable(drawable)
188 | }
189 | drawable = wrap(drawable)
190 | return drawable
191 | }
192 |
193 | private fun getSolidColorStateList(): ColorStateList {
194 | if (properties.solidColorStateList != null) {
195 | return properties.solidColorStateList!!
196 | }
197 |
198 | val states = mutableListOf()
199 | val colors = mutableListOf()
200 |
201 | solidColorPressed?.let {
202 | states.add(intArrayOf(android.R.attr.state_pressed))
203 | colors.add(it)
204 | }
205 | solidColorDisabled?.let {
206 | states.add(intArrayOf(-android.R.attr.state_enabled))
207 | colors.add(it)
208 | }
209 | solidColorSelected?.let {
210 | states.add(intArrayOf(android.R.attr.state_selected))
211 | colors.add(it)
212 | }
213 | states.add(StateSet.WILD_CARD)
214 | colors.add(properties.solidColor)
215 |
216 | return ColorStateList(states.toTypedArray(), colors.toIntArray())
217 | }
218 |
219 | private fun getStrokeColorStateList(): ColorStateList {
220 | if (properties.strokeColorStateList != null) {
221 | return properties.strokeColorStateList!!
222 | }
223 |
224 | val states = mutableListOf()
225 | val colors = mutableListOf()
226 |
227 | strokeColorPressed?.let {
228 | states.add(intArrayOf(android.R.attr.state_pressed))
229 | colors.add(it)
230 | }
231 | strokeColorDisabled?.let {
232 | states.add(intArrayOf(-android.R.attr.state_enabled))
233 | colors.add(it)
234 | }
235 | strokeColorSelected?.let {
236 | states.add(intArrayOf(android.R.attr.state_selected))
237 | colors.add(it)
238 | }
239 | states.add(StateSet.WILD_CARD)
240 | colors.add(properties.strokeColor)
241 |
242 | return ColorStateList(states.toTypedArray(), colors.toIntArray())
243 | }
244 |
245 | private fun buildPressedDrawable(): Drawable? {
246 | if (solidColorPressed == null && strokeColorPressed == null) return null
247 |
248 | val pressedDrawable = GradientDrawable()
249 | setupGradientDrawable(pressedDrawable)
250 | solidColorPressed?.let {
251 | pressedDrawable.setColor(it)
252 | }
253 | strokeColorPressed?.let {
254 | setStrokeColor(pressedDrawable, it)
255 | }
256 | return pressedDrawable
257 | }
258 |
259 | private fun buildDisabledDrawable(): Drawable? {
260 | if (solidColorDisabled == null && strokeColorDisabled == null) return null
261 |
262 | val disabledDrawable = GradientDrawable()
263 | setupGradientDrawable(disabledDrawable)
264 | solidColorDisabled?.let {
265 | disabledDrawable.setColor(it)
266 | }
267 | strokeColorDisabled?.let {
268 | setStrokeColor(disabledDrawable, it)
269 | }
270 | return disabledDrawable
271 | }
272 |
273 | private fun buildSelectedDrawable(): Drawable? {
274 | if (solidColorSelected == null && strokeColorSelected == null) return null
275 |
276 | val selectedDrawable = GradientDrawable()
277 | setupGradientDrawable(selectedDrawable)
278 | solidColorSelected?.let {
279 | selectedDrawable.setColor(it)
280 | }
281 | strokeColorSelected?.let {
282 | setStrokeColor(selectedDrawable, it)
283 | }
284 | return selectedDrawable
285 | }
286 |
287 | private fun buildNormalDrawable(): Drawable {
288 | val pressedDrawable = GradientDrawable()
289 | setupGradientDrawable(pressedDrawable)
290 | return pressedDrawable
291 | }
292 |
293 | private fun setupGradientDrawable(drawable: GradientDrawable) {
294 | properties.apply {
295 | drawable.shape = shape
296 | if (shape == GradientDrawable.RING) {
297 | setInnerRadius(drawable, innerRadius)
298 | setInnerRadiusRatio(drawable, innerRadiusRatio)
299 | setThickness(drawable, thickness)
300 | setThicknessRatio(drawable, thicknessRatio)
301 | setUseLevelForShape(drawable, useLevelForRing)
302 | }
303 | drawable.cornerRadii = getCornerRadii()
304 | if (useGradient) {
305 | drawable.gradientType = type
306 | setGradientRadiusType(drawable, gradientRadiusType)
307 | setGradientRadius(drawable, gradientRadius)
308 | drawable.setGradientCenter(centerX, centerY)
309 | setOrientation(drawable, getOrientation())
310 | setColors(drawable, getColors())
311 | drawable.useLevel = useLevelForGradient
312 | } else {
313 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
314 | drawable.color = getSolidColorStateList()
315 | } else {
316 | drawable.setColor(solidColor)
317 | }
318 | }
319 | drawable.setSize(width, height)
320 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
321 | drawable.setStroke(strokeWidth, getStrokeColorStateList(), dashWidth.toFloat(), dashGap.toFloat())
322 | } else {
323 | drawable.setStroke(strokeWidth, strokeColor, dashWidth.toFloat(), dashGap.toFloat())
324 | }
325 | }
326 | }
327 |
328 | private fun needStateListDrawable(): Boolean {
329 | return Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP
330 | && (hasStrokeColorStateList() || (!properties.useGradient && hasSolidColorStateList()))
331 | }
332 |
333 | private fun needRotateDrawable(): Boolean {
334 | return properties.useRotate &&
335 | !(properties.pivotX == 0.5f && properties.pivotY == 0.5f
336 | && properties.fromDegrees == 0f && properties.toDegrees == 0f)
337 | }
338 |
339 | private fun needScaleDrawable(): Boolean {
340 | return properties.useScale
341 | }
342 |
343 | private fun wrap(drawable: Drawable): Drawable {
344 | var wrappedDrawable = drawable
345 |
346 | if (rotateOrder > 0) {
347 | transformsMap[rotateOrder] = ::wrapRotateIfNeeded
348 | }
349 | if (scaleOrder > 0) {
350 | transformsMap[scaleOrder] = ::wrapScaleIfNeeded
351 | }
352 |
353 | for (action in transformsMap.values) {
354 | wrappedDrawable = action.invoke(wrappedDrawable)
355 | }
356 |
357 | if (properties.useFlip) {
358 | wrappedDrawable = FlipDrawableBuilder()
359 | .drawable(wrappedDrawable)
360 | .orientation(properties.orientation)
361 | .build()
362 | }
363 |
364 | if (isRippleSupported() && properties.useRipple) {
365 | wrappedDrawable = RippleDrawableBuilder()
366 | .drawable(wrappedDrawable)
367 | .color(properties.rippleColor)
368 | .colorStateList(properties.rippleColorStateList)
369 | .radius(properties.rippleRadius)
370 | .build()
371 | }
372 |
373 | return wrappedDrawable
374 | }
375 |
376 | private fun shouldFallbackRipple(): Boolean {
377 | return properties.useRipple && !isRippleSupported()
378 | }
379 |
380 | private fun isRippleSupported(): Boolean {
381 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
382 | }
383 |
384 | private fun wrapRotateIfNeeded(drawable: Drawable): Drawable {
385 | if (!needRotateDrawable()) return drawable
386 |
387 | with(properties) {
388 | return RotateDrawableBuilder()
389 | .drawable(drawable)
390 | .pivotX(pivotX)
391 | .pivotY(pivotY)
392 | .fromDegrees(fromDegrees)
393 | .toDegrees(toDegrees)
394 | .build()
395 | }
396 | }
397 |
398 | private fun wrapScaleIfNeeded(drawable: Drawable): Drawable {
399 | if (!needScaleDrawable()) return drawable
400 |
401 | with(properties) {
402 | return ScaleDrawableBuilder()
403 | .drawable(drawable)
404 | .level(scaleLevel)
405 | .scaleGravity(scaleGravity)
406 | .scaleWidth(scaleWidth)
407 | .scaleHeight(scaleHeight)
408 | .build()
409 | }
410 | }
411 |
412 | private fun hasSolidColorStateList(): Boolean {
413 | return solidColorPressed != null || solidColorDisabled != null || solidColorSelected != null
414 | }
415 |
416 | private fun hasStrokeColorStateList(): Boolean {
417 | return strokeColorPressed != null || strokeColorDisabled != null || strokeColorSelected != null
418 | }
419 | }
--------------------------------------------------------------------------------