Repository: L-Briand/ShadowLayout Branch: master Commit: 2ceb317bdb0d Files: 38 Total size: 55.5 KB Directory structure: gitextract_6iuvvsg5/ ├── .gitignore ├── .idea/ │ ├── codeStyles/ │ │ ├── Project.xml │ │ └── codeStyleConfig.xml │ ├── gradle.xml │ ├── jarRepositories.xml │ └── runConfigurations.xml ├── LICENSE ├── README.MD ├── build.gradle ├── consumer-rules.pro ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── proguard-rules.pro ├── sample/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── net/ │ │ └── orandja/ │ │ └── shadowlayout/ │ │ └── sample/ │ │ └── MainActivity.kt │ └── res/ │ ├── drawable/ │ │ ├── ic_launcher_background.xml │ │ ├── ic_launcher_foreground.xml │ │ ├── multicolor.xml │ │ └── round_corners.xml │ ├── layout/ │ │ └── activity_main.xml │ ├── mipmap-anydpi-v26/ │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ └── values/ │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── settings.gradle └── shadowlayout/ ├── .gitignore ├── build.gradle └── src/ └── main/ ├── AndroidManifest.xml ├── java/ │ └── net/ │ └── orandja/ │ └── shadowlayout/ │ ├── ShadowLayout.kt │ └── Utils.kt └── res/ └── values/ └── attrs.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Created by https://www.toptal.com/developers/gitignore/api/androidstudio # Edit at https://www.toptal.com/developers/gitignore?templates=androidstudio ### AndroidStudio ### # Covers files to be ignored for android development using Android Studio. # Built application files *.apk *.ap_ # Files for the ART/Dalvik VM *.dex # Java class files *.class # Generated files bin/ gen/ out/ # Gradle files .gradle .gradle/ build/ # Signing files .signing/ # Local configuration file (sdk path, etc) local.properties # Proguard folder generated by Eclipse proguard/ # Log Files *.log # Android Studio /*/build/ /*/local.properties /*/out /*/*/build /*/*/production captures/ .navigation/ *.ipr *~ *.swp # Android Patch gen-external-apklibs # External native build folder generated in Android Studio 2.2 and later .externalNativeBuild # NDK obj/ # IntelliJ IDEA *.iml *.iws /out/ # User-specific configurations .idea/caches/ .idea/libraries/ .idea/shelf/ .idea/workspace.xml .idea/tasks.xml .idea/.name .idea/compiler.xml .idea/copyright/profiles_settings.xml .idea/encodings.xml .idea/misc.xml .idea/modules.xml .idea/scopes/scope_settings.xml .idea/dictionaries .idea/vcs.xml .idea/jsLibraryMappings.xml .idea/datasources.xml .idea/dataSources.ids .idea/sqlDataSources.xml .idea/dynamic.xml .idea/uiDesigner.xml .idea/assetWizardSettings.xml # OS-specific files .DS_Store .DS_Store? ._* .Spotlight-V100 .Trashes ehthumbs.db Thumbs.db # Legacy Eclipse project files .classpath .project .cproject .settings/ # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.war *.ear # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml) hs_err_pid* ## Plugin-specific files: # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Mongo Explorer plugin .idea/mongoSettings.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties ### AndroidStudio Patch ### !/gradle/wrapper/gradle-wrapper.jar # End of https://www.toptal.com/developers/gitignore/api/androidstudio ================================================ FILE: .idea/codeStyles/Project.xml ================================================ ================================================ FILE: .idea/codeStyles/codeStyleConfig.xml ================================================ ================================================ FILE: .idea/gradle.xml ================================================ ================================================ FILE: .idea/jarRepositories.xml ================================================ ================================================ FILE: .idea/runConfigurations.xml ================================================ ================================================ FILE: LICENSE ================================================ BSD 3-Clause License Copyright (c) 2020, Lionel Briand All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: README.MD ================================================ # ShadowLayout a css like shadow for android Have you ever wanted a CSS type of shadow in your Android project ? No?! Me neither but designers keep using it and the death flag is triggered when the app isn't a copy of the design. So, there it goes. It do much more than casting a shadow so the name can be inaccurate. Internally, it uses the native `ScriptIntrinsicBlur` render script so it can easily blur the whole layout like the [Blurry](https://github.com/wasabeef/Blurry) library. # Requirements Android 5.+ (API 21) # Gradle The project is hosted on maven Central : ```groovy allprojects { repositories { mavenCentral() } } ``` Then add dependency : ```groovy dependencies { implementation("net.orandja.shadowlayout:shadowlayout:1.0.1") } ``` # Usage Add `android:clipChildren="false"`, `android:clipToPadding="false"` to the parent layout to let ShadowLayout draw outside of view bounds. ```xml ``` ![quick brown fox text view](assets/quick_fox.png) ## Parameters Default value in parenthesis - `shadow_radius` (6f) The radius of the gaussian blur in float. See #Rules of downscaling section to see how it works. - `shadow_x_shift` (0dp) Shift on the horizontal axis in dp - `shadow_y_shift` (0dp) Shift on the vertical axis in dp - `shadow_color` (#33000000) Color of the casted shadow - `shadow_downscale` (1f) Downscale of the internal bitmap that render the shadow. The higher the downscale, the lower in size is the bitmap. At 2, the size of bitmap is halved. - `shadow_with_foreground` (true) Draw the actual view on top of the shadow. - `shadow_with_color` (false) Keep all the subview colors in the blur. Coupled with `shadow_with_foreground` at false, a blur image can be render on screen. - `shadow_with_dpi_scale` (true) Downscale the internal bitmap by the current smartphone dpi. A 100dp view will result in a 100px bitmap. - `shadow_with_css_scale` (true) Downscale by 5/3 more. Because CSS shadow standard blur by a half more than the real blur size. - `shadow_cast_only_background` (false) Only render the background and not the view as shadow ## Limitations The default implementation of android gaussian blur (`ScriptIntrinsicBlur` render script) is limited to 25 pixels at max. To counter that, the layout downscale the real render of the view inside a bitmap (ALPHA_8 or RGBA with `shadow_with_color` at true). Then blur it. Then renders the blur inside the canvas. Then **redraw** the view in the canvas. (`shadow_with_foreground` at true) The radius can mean multiple things depending on the configurations. ## Rules of downscaling When no downscale are applied: ```xml ``` The internal bitmap is the same size of the view. The radius is the number of **pixels** blured around. With high dpi, it will be hard to see the effect. However, in some cases, it can be usefull to have a nice looking blur at the expense of more memory. The max radius is 25 pixels. The parameter `shadow_downscale` multiply the max radius by its value. So at shadow_downscale="2.5" it increases the max radius to 62.5f. When `app:shadow_with_dpi_scale="true"`: Downscale the internal bitmap by the current smartphone dpi. A 100dp view will result in a 100px bitmap. The radius means **dp**. It blurs up to 25dp. When `app:shadow_with_css_scale="true"`: Same as dpi, it will add a 5/3 downscale to mimic the CSS shadow blur. # Shadow anything As said before since it draw the whole layout it can cast a shadow of anything. Like text: ```xml ``` ![quick brown fox text view](assets/quick_fox_text.png) Since `shadow_with_color` is at true, the drawn shadow is of the same color of the text rendered. The color parameter only affect alpha. ================================================ FILE: build.gradle ================================================ buildscript { ext.kotlin_version = '1.5.0' repositories { google() mavenCentral() } dependencies { classpath 'com.vanniktech:gradle-maven-publish-plugin:0.15.1' classpath 'com.android.tools.build:gradle:4.2.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() mavenCentral() } } ================================================ FILE: consumer-rules.pro ================================================ ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Sat Jun 20 19:39:00 CEST 2020 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-all.zip ================================================ FILE: gradle.properties ================================================ org.gradle.jvmargs=-Xmx1536m android.useAndroidX=true android.enableJetifier=true kotlin.code.style=official GROUP=net.orandja.shadowlayout POM_ARTIFACT_ID=shadowlayout VERSION_NAME=1.0.1 POM_NAME=Shadow Layout POM_DESCRIPTION=ShadowLayout a css like shadow for android POM_INCEPTION_YEAR=2020 POM_URL=https://github.com/L-Briand/ShadowLayout POM_LICENCE_NAME=BSD 3-Clause License POM_LICENCE_URL=https://opensource.org/licenses/BSD-3-Clause POM_LICENCE_DIST=repo POM_SCM_URL=https://github.com/L-Briand/ShadowLayout POM_SCM_CONNECTION=scm:git:git://github.com/L-Briand/ShadowLayout.git POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/L-Briand/ShadowLayout.git POM_DEVELOPER_ID=L-Briand POM_DEVELOPER_NAME=Lionel Briand POM_DEVELOPER_URL=https://github.com/L-Briand ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=$(save "$@") # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: sample/.gitignore ================================================ /build ================================================ FILE: sample/build.gradle ================================================ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' android { compileSdkVersion 30 buildToolsVersion "30.0.3" defaultConfig { applicationId "fr.orandja.shadowlayout.sample" minSdkVersion 21 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation 'androidx.core:core-ktx:1.5.0' implementation 'androidx.appcompat:appcompat:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' implementation project(':shadowlayout') } ================================================ FILE: sample/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: sample/src/main/AndroidManifest.xml ================================================ ================================================ FILE: sample/src/main/java/net/orandja/shadowlayout/sample/MainActivity.kt ================================================ package net.orandja.shadowlayout.sample import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import net.orandja.shadowlayout.ShadowLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) ValueAnimator.ofFloat(0f, 0f, 25f, 25f).apply { duration = 2000 repeatCount = ObjectAnimator.INFINITE repeatMode = ObjectAnimator.REVERSE addUpdateListener { findViewById(R.id.__rainbow).shadow_radius = it.animatedValue as Float } }.start() } } ================================================ FILE: sample/src/main/res/drawable/ic_launcher_background.xml ================================================ ================================================ FILE: sample/src/main/res/drawable/ic_launcher_foreground.xml ================================================ ================================================ FILE: sample/src/main/res/drawable/multicolor.xml ================================================ ================================================ FILE: sample/src/main/res/drawable/round_corners.xml ================================================ ================================================ FILE: sample/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml ================================================ ================================================ FILE: sample/src/main/res/values/colors.xml ================================================ #6200EE #3700B3 #03DAC5 ================================================ FILE: sample/src/main/res/values/strings.xml ================================================ sample ================================================ FILE: sample/src/main/res/values/styles.xml ================================================ ================================================ FILE: settings.gradle ================================================ rootProject.name = "ShadowLayout" include ":shadowlayout", ":sample" ================================================ FILE: shadowlayout/.gitignore ================================================ /build ================================================ FILE: shadowlayout/build.gradle ================================================ plugins { id 'com.android.library' id 'kotlin-android' id 'com.vanniktech.maven.publish' } android { compileSdkVersion 30 buildToolsVersion "30.0.3" compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = JavaVersion.VERSION_1_8 } defaultConfig { minSdkVersion 21 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles 'consumer-rules.pro' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.core:core-ktx:1.5.0' } ================================================ FILE: shadowlayout/src/main/AndroidManifest.xml ================================================ ================================================ FILE: shadowlayout/src/main/java/net/orandja/shadowlayout/ShadowLayout.kt ================================================ package net.orandja.shadowlayout import android.content.Context import android.content.res.Resources import android.graphics.* import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsicBlur import android.util.AttributeSet import android.util.DisplayMetrics import android.view.View import android.view.ViewOutlineProvider import android.widget.FrameLayout import androidx.annotation.ColorRes import androidx.annotation.DimenRes import androidx.annotation.Nullable import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.scaleMatrix import androidx.core.graphics.times import androidx.core.graphics.translationMatrix import androidx.core.graphics.withMatrix import kotlin.math.ceil /** A CSS like shadow */ @Suppress("PropertyName") class ShadowLayout @JvmOverloads constructor( context: Context, @Nullable attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.shadowLayoutStyle, defStyleRes: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr, defStyleRes) { companion object { @JvmField val ratioDpToPixels = Resources.getSystem().displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT @JvmField val ratioPixelsToDp: Float = (1.0 / ratioDpToPixels.toDouble()).toFloat() // Thanks to this hero https://stackoverflow.com/a/41322648/4681367 const val cssRatio: Float = 5f / 3f } // BASIC FIELDS private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG) private val eraser = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT) } var shadow_color: Int get() = paint.color set(value) { if (paint.color == value) return paint.color = value postInvalidate() } fun setColorRes(@ColorRes color: Int) { shadow_color = ResourcesCompat.getColor(resources, color, context.theme) } var shadow_x_shift: Float by OnUpdate(0f) fun setXShift(@DimenRes shift: Int) { shadow_x_shift = context.resources.getDimension(shift) } var shadow_y_shift: Float by OnUpdate(0f) fun setYShift(@DimenRes shift: Int) { shadow_y_shift = context.resources.getDimension(shift) } var shadow_downscale: Float by OnUpdate(1f, { it.coerceAtLeast(0.1f) }) { realRadius = shadow_radius / it updateBitmap() } var shadow_radius: Float by OnUpdate(0f, { it.coerceAtLeast(0f) }) { realRadius = it / shadow_downscale } private var realRadius: Float by OnUpdate( 0f, { it.coerceIn(0f, 25f) } // allowed blur size on ScriptIntrinsicBlur by android ) var shadow_cast_only_background: Boolean by OnUpdate(false) var shadow_with_content: Boolean by OnUpdate(true) var shadow_with_color: Boolean by OnUpdate(false) { destroyBitmap() updateBitmap() } var shadow_with_dpi_scale: Boolean by OnUpdate(true) { destroyBitmap() updateBitmap() } var shadow_with_css_scale: Boolean by OnUpdate(true) { destroyBitmap() updateBitmap() } // IN VARIABLES private val ratioDpToPixels get() = if (shadow_with_dpi_scale) Companion.ratioDpToPixels else 1f private val ratioPixelsToDp get() = if (shadow_with_dpi_scale) Companion.ratioPixelsToDp else 1f private val cssRatio get() = if (shadow_with_css_scale) Companion.cssRatio else 1f // size in pixel of the blur spread private val pixelsOverBoundaries: Int get() = if (shadow_downscale < 1f) 25 else ceil(25f * shadow_downscale).toInt() private val viewBounds: Rect = Rect() private fun setViewBounds(width: Int, height: Int) { viewBounds.set(0, 0, width, height) updateBitmap() } private var blurBitmap: Bitmap? = null private var blurCanvas: Canvas? = null private var renderScript: RenderScript? = null; private var script: ScriptIntrinsicBlur? = null; private var inAlloc: Allocation? = null private var outAlloc: Allocation? = null private var lastWithColorScript: Boolean? = null private fun getScript(): Pair { val renderScript = this.renderScript ?: RenderScript.create(context) if (lastWithColorScript != shadow_with_color) { // recreate script only if colors change lastWithColorScript = shadow_with_color script = null } if (script != null) return Pair(script!!, renderScript!!) val element = if (shadow_with_color) Element.U8_4(renderScript) else Element.U8(renderScript) script = ScriptIntrinsicBlur.create(renderScript, element) return Pair(script!!, renderScript!!) } private val lastBounds = Rect() private var lastScale = 0f private var lastWithColorBitmap: Boolean? = null private var lastWithDpi: Boolean? = null private var lastWithCss: Boolean? = null private fun updateBitmap() { // do not recreate if same specs. if (viewBounds.isEmpty || isAttachedToWindow && lastBounds == viewBounds && shadow_downscale == lastScale && shadow_with_color == lastWithColorBitmap && shadow_with_dpi_scale == lastWithDpi && shadow_with_css_scale == lastWithCss ) return lastBounds.set(viewBounds) lastScale = shadow_downscale lastWithColorBitmap = shadow_with_color lastWithColorBitmap = shadow_with_color lastWithDpi = shadow_with_dpi_scale lastWithCss = shadow_with_css_scale // create a receptacle for blur script. (MDPI / downscale) + (pixels * 2) cause blur spread in all directions blurBitmap?.recycle() blurBitmap = Bitmap.createBitmap( (ceil( (viewBounds.width().toFloat() * ratioPixelsToDp) / shadow_downscale / cssRatio ) + pixelsOverBoundaries * 2).toInt(), (ceil( (viewBounds.height().toFloat() * ratioPixelsToDp) / shadow_downscale / cssRatio ) + pixelsOverBoundaries * 2).toInt(), if (shadow_with_color) Bitmap.Config.ARGB_8888 else Bitmap.Config.ALPHA_8 ) blurCanvas = Canvas(blurBitmap!!) val (script, renderScript) = getScript() inAlloc?.destroy() inAlloc = Allocation.createFromBitmap(renderScript, blurBitmap) if (outAlloc?.type != inAlloc?.type) { outAlloc?.destroy() outAlloc = Allocation.createTyped(renderScript, inAlloc!!.type) } script.setInput(inAlloc) } private fun destroyBitmap() { blurBitmap?.recycle() blurBitmap = null blurCanvas = null script?.destroy() script = null inAlloc?.destroy() inAlloc = null outAlloc?.destroy() outAlloc = null lastBounds.setEmpty() lastScale = 0f lastWithColorScript = null lastWithColorBitmap = null lastWithDpi = null lastWithCss = null } /** Cause the default elevation rendering to not work */ override fun getOutlineProvider(): ViewOutlineProvider = object : ViewOutlineProvider() { override fun getOutline(view: View?, outline: Outline?) = Unit } // Overriding view init { if (!isInEditMode) { val attributes = context.obtainStyledAttributes( attrs, R.styleable.ShadowLayout, defStyleAttr, defStyleRes ) shadow_color = attributes.getColor(R.styleable.ShadowLayout_shadow_color, 51 shl 24) shadow_with_color = attributes.getBoolean(R.styleable.ShadowLayout_shadow_with_color, false) shadow_with_content = attributes.getBoolean(R.styleable.ShadowLayout_shadow_with_content, true) shadow_with_dpi_scale = attributes.getBoolean(R.styleable.ShadowLayout_shadow_with_dpi_scale, true) shadow_with_css_scale = attributes.getBoolean(R.styleable.ShadowLayout_shadow_with_css_scale, true) shadow_x_shift = attributes.getDimension(R.styleable.ShadowLayout_shadow_x_shift, 0f) shadow_y_shift = attributes.getDimension(R.styleable.ShadowLayout_shadow_y_shift, 0f) shadow_downscale = attributes.getFloat(R.styleable.ShadowLayout_shadow_downscale, 1f) shadow_radius = attributes.getFloat(R.styleable.ShadowLayout_shadow_radius, 6f) shadow_cast_only_background = attributes.getBoolean(R.styleable.ShadowLayout_shadow_cast_only_background, false) attributes.recycle() } setWillNotDraw(false) } override fun onAttachedToWindow() { super.onAttachedToWindow() if (!isInEditMode) updateBitmap() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() if (!isInEditMode) destroyBitmap() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) if (!isInEditMode) setViewBounds(w, h) } private inline val blurTMatrix: Matrix // cause blur spreads get() = translationMatrix(pixelsOverBoundaries.toFloat(), pixelsOverBoundaries.toFloat()) private inline val blurSMatrix: Matrix // to draw inside the small blurBitmap get() = scaleMatrix(ratioPixelsToDp / shadow_downscale / cssRatio, ratioPixelsToDp / shadow_downscale / cssRatio) private inline val drawTMatrix: Matrix // counterbalance for blur spread in canvas get() = translationMatrix( -(pixelsOverBoundaries * ratioDpToPixels * shadow_downscale * cssRatio), -(pixelsOverBoundaries * ratioDpToPixels * shadow_downscale * cssRatio) ) private inline val drawSMatrix: Matrix // enlarge blur image to canvas size get() = scaleMatrix( ratioDpToPixels * shadow_downscale * cssRatio, ratioDpToPixels * shadow_downscale * cssRatio ) private inline val shiftTMatrix: Matrix // User want a nice shifted shadow get() = translationMatrix( shadow_x_shift / shadow_downscale / cssRatio, shadow_y_shift / shadow_downscale / cssRatio ) override fun draw(canvas: Canvas?) { canvas ?: return if (isInEditMode) { super.draw(canvas) return } if (blurCanvas != null) { blurCanvas!!.drawRect(blurCanvas!!.clipBounds, eraser) blurCanvas!!.withMatrix(blurTMatrix * blurSMatrix) { if (shadow_cast_only_background) { background.bounds = viewBounds background?.draw(blurCanvas!!) } else super.draw(blurCanvas) } if (realRadius > 0f) { // Do not blur if no radius val (script) = getScript() script.setRadius(realRadius) inAlloc?.copyFrom(blurBitmap) script.forEach(outAlloc) outAlloc?.copyTo(blurBitmap) } canvas.withMatrix(drawTMatrix * drawSMatrix * shiftTMatrix) { canvas.drawBitmap(blurBitmap!!, 0f, 0f, paint) } } if (shadow_with_content) super.draw(canvas) } } ================================================ FILE: shadowlayout/src/main/java/net/orandja/shadowlayout/Utils.kt ================================================ package net.orandja.shadowlayout import android.view.View import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty internal class OnUpdate(default: T, val transformation: ((T) -> T)? = null, val onUpdate: ((T) -> Unit)? = null) : ReadWriteProperty { var backing: T = default override fun getValue(thisRef: View, property: KProperty<*>): T = backing override fun setValue(thisRef: View, property: KProperty<*>, value: T) { if (backing == value) return backing = transformation?.invoke(value) ?: value onUpdate?.invoke(value) thisRef.postInvalidate() } } ================================================ FILE: shadowlayout/src/main/res/values/attrs.xml ================================================