├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ └── ic_launcher.png │ │ │ └── layout │ │ │ │ └── activity_sample.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── info │ │ │ └── hellovass │ │ │ └── snowingview │ │ │ └── demo │ │ │ └── SampleActivity.java │ ├── test │ │ └── java │ │ │ └── info │ │ │ └── hellovass │ │ │ └── snowingview │ │ │ └── demo │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── info │ │ └── hellovass │ │ └── snowingview │ │ └── demo │ │ └── ApplicationTest.java ├── build.gradle └── proguard-rules.pro ├── snowingview ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ └── attrs.xml │ │ │ ├── drawable-xxxhdpi │ │ │ │ └── ic_snowflake.png │ │ │ └── xml │ │ │ │ └── snowing_paper.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── info │ │ │ └── hellovass │ │ │ └── snowingview │ │ │ ├── utils │ │ │ ├── ScreenUtil.java │ │ │ ├── DensityUtil.java │ │ │ └── RandomUtil.java │ │ │ └── widgets │ │ │ ├── SnowFlake.java │ │ │ ├── SnowingView.java │ │ │ ├── SnowingSurfaceView.java │ │ │ └── SnowingPaperService.java │ ├── test │ │ └── java │ │ │ └── info │ │ │ └── hellovass │ │ │ └── snowingview │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── info │ │ └── hellovass │ │ └── snowingview │ │ └── ApplicationTest.java ├── build.gradle └── proguard-rules.pro ├── settings.gradle ├── apk └── app-debug.apk ├── .gitignore ├── design └── snowingwallpaper.gif ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── README.md ├── gradlew.bat └── gradlew /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /snowingview/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':snowingview' 2 | -------------------------------------------------------------------------------- /apk/app-debug.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeasonWong/SnowingView/HEAD/apk/app-debug.apk -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | -------------------------------------------------------------------------------- /design/snowingwallpaper.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeasonWong/SnowingView/HEAD/design/snowingwallpaper.gif -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | SnowingView 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeasonWong/SnowingView/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /snowingview/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | snowingview 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeasonWong/SnowingView/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeasonWong/SnowingView/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeasonWong/SnowingView/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeasonWong/SnowingView/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeasonWong/SnowingView/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /snowingview/src/main/res/drawable-xxxhdpi/ic_snowflake.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeasonWong/SnowingView/HEAD/snowingview/src/main/res/drawable-xxxhdpi/ic_snowflake.png -------------------------------------------------------------------------------- /snowingview/src/main/res/xml/snowing_paper.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /snowingview/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Aug 16 11:38:02 CST 2016 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-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /app/src/test/java/info/hellovass/snowingview/demo/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.demo; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test public void addition_isCorrect() throws Exception { 12 | assertEquals(4, 2 + 2); 13 | } 14 | } -------------------------------------------------------------------------------- /snowingview/src/test/java/info/hellovass/snowingview/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test public void addition_isCorrect() throws Exception { 12 | assertEquals(4, 2 + 2); 13 | } 14 | } -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/androidTest/java/info/hellovass/snowingview/demo/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.demo; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /snowingview/src/androidTest/java/info/hellovass/snowingview/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /snowingview/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 24 5 | buildToolsVersion "24.0.2" 6 | 7 | defaultConfig { 8 | minSdkVersion 16 9 | targetSdkVersion 24 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | compile fileTree(include: ['*.jar'], dir: 'libs') 23 | testCompile 'junit:junit:4.12' 24 | compile 'com.android.support:appcompat-v7:24.2.1' 25 | compile 'io.reactivex:rxandroid:1.2.1' 26 | } 27 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 24 5 | buildToolsVersion "24.0.2" 6 | 7 | defaultConfig { 8 | applicationId "info.hellovass.snowingview.demo" 9 | minSdkVersion 16 10 | targetSdkVersion 24 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(include: ['*.jar'], dir: 'libs') 24 | testCompile 'junit:junit:4.12' 25 | compile 'com.android.support:appcompat-v7:24.2.1' 26 | compile project(':snowingview') 27 | } 28 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/HelloVass/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /snowingview/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/HelloVass/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /snowingview/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 14 | 15 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /snowingview/src/main/java/info/hellovass/snowingview/utils/ScreenUtil.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.utils; 2 | 3 | import android.content.Context; 4 | import android.util.DisplayMetrics; 5 | 6 | /** 7 | * Created by HelloVass on 16/3/3. 8 | */ 9 | public class ScreenUtil { 10 | 11 | private ScreenUtil() { 12 | 13 | } 14 | 15 | /** 16 | * 得到屏幕的宽度 17 | * 18 | * @param context 上下文 19 | * @return 屏幕的宽度,单位像素 20 | */ 21 | public static int getScreenWidth(Context context) { 22 | DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); 23 | return displayMetrics.widthPixels; 24 | } 25 | 26 | /** 27 | * 得到屏幕的高度 28 | * 29 | * @param context 上下文 30 | * @return 屏幕的高度,单位像素 31 | */ 32 | public static int getScreenHeight(Context context) { 33 | DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); 34 | return displayMetrics.heightPixels; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /snowingview/src/main/java/info/hellovass/snowingview/utils/DensityUtil.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.utils; 2 | 3 | import android.content.Context; 4 | 5 | /** 6 | * Created by HelloVass on 16/1/15. 7 | * 8 | * 分辨率转换工具 9 | */ 10 | public class DensityUtil { 11 | 12 | private DensityUtil() { 13 | 14 | } 15 | 16 | /** 17 | * 将 px 转换为 dp 18 | * 19 | * @param context 上下文 20 | * @param px 像素 21 | * @return dp 22 | */ 23 | public static int px2dip(Context context, float px) { 24 | 25 | float scale = context.getResources().getDisplayMetrics().density; 26 | return (int) (px / scale + 0.5f); 27 | } 28 | 29 | /** 30 | * 将 dp 转换为 px 31 | * 32 | * @param context 上下文 33 | * @param dp 像素 34 | * @return px 35 | */ 36 | public static int dip2px(Context context, float dp) { 37 | float scale = context.getResources().getDisplayMetrics().density; 38 | return (int) (dp * scale + 0.5f); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_sample.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 17 | 18 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /snowingview/src/main/java/info/hellovass/snowingview/utils/RandomUtil.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.utils; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * Created by hellovass on 16/9/27. 7 | */ 8 | 9 | public class RandomUtil { 10 | 11 | private static final Random RANDOM = new Random(); 12 | 13 | private RandomUtil() { 14 | 15 | } 16 | 17 | public static int nextInt(int startInclusive) { 18 | return RANDOM.nextInt(startInclusive); 19 | } 20 | 21 | public static float nextFloat(float startInclusive) { 22 | return RANDOM.nextFloat() * startInclusive; 23 | } 24 | 25 | public static int nextInt(int startInclusive, int endExclusive) { 26 | return startInclusive == endExclusive ? startInclusive 27 | : startInclusive + RANDOM.nextInt(endExclusive - startInclusive); 28 | } 29 | 30 | public static float nextFloat(float startInclusive, float endInclusive) { 31 | return startInclusive == endInclusive ? startInclusive 32 | : startInclusive + (endInclusive - startInclusive) * RANDOM.nextFloat(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## What's SnowingView ? 2 | It's a dynamic wallpaper with snowing fall down effect and accelerometer sensor. 3 | 4 | ## Install 5 | [apk](./apk/app-debug.apk) 6 | 7 | ## Demo 8 | ![SnowingView](./design/snowingwallpaper.gif) 9 | 10 | ## 中文介绍 11 | - 三种方式实现雪花掉落效果(原作者的View,我补充的SurfaceView以及WallpaperService) 12 | - 拥有加速度传感器,效果更酷 13 | 14 | ## Blog 15 | [手摸手教你做动态壁纸](http://www.wangyuwei.me/2016/09/30/%E6%89%8B%E6%91%B8%E6%89%8B%E6%95%99%E4%BD%A0%E5%81%9A%E5%8A%A8%E6%80%81%E5%A3%81%E7%BA%B8/) 16 | 17 | ### About Me 18 | 19 | [Weibo](http://weibo.com/WongYuwei) 20 | 21 | [Blog](http://www.wangyuwei.me) 22 | 23 | ### QQ Group 欢迎讨论 24 | 25 | **479729938** 26 | 27 | ##**License** 28 | 29 | ```license 30 | Copyright [2016] [JeasonWong of copyright owner] 31 | 32 | Licensed under the Apache License, Version 2.0 (the "License"); 33 | you may not use this file except in compliance with the License. 34 | You may obtain a copy of the License at 35 | 36 | http://www.apache.org/licenses/LICENSE-2.0 37 | 38 | Unless required by applicable law or agreed to in writing, software 39 | distributed under the License is distributed on an "AS IS" BASIS, 40 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 41 | See the License for the specific language governing permissions and 42 | limitations under the License. 43 | ``` 44 | -------------------------------------------------------------------------------- /app/src/main/java/info/hellovass/snowingview/demo/SampleActivity.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.demo; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.widget.CompoundButton; 7 | import android.widget.Switch; 8 | 9 | import info.hellovass.snowingview.widgets.SnowingSurfaceView; 10 | 11 | /** 12 | * Created by HelloVass on 16/8/15. 13 | */ 14 | public class SampleActivity extends AppCompatActivity { 15 | 16 | private SnowingSurfaceView mSnowingView; 17 | 18 | private Switch mSwitch; 19 | 20 | @Override 21 | protected void onCreate(@Nullable Bundle savedInstanceState) { 22 | super.onCreate(savedInstanceState); 23 | setContentView(R.layout.activity_sample); 24 | 25 | mSwitch = (Switch) findViewById(R.id.sw_snowing); 26 | mSnowingView = (SnowingSurfaceView) findViewById(R.id.snowing_view); 27 | 28 | mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 29 | @Override 30 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 31 | 32 | if (isChecked) { 33 | mSnowingView.startFall(); 34 | } else { 35 | mSnowingView.stopFall(); 36 | } 37 | } 38 | }); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /snowingview/src/main/java/info/hellovass/snowingview/widgets/SnowFlake.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.widgets; 2 | 3 | /** 4 | * Created by hellovass on 16/9/26. 5 | */ 6 | 7 | public class SnowFlake { 8 | 9 | private float mPositionX; 10 | 11 | private float mPositionY; 12 | 13 | private float mVelocityY; 14 | 15 | private int mTransparency; 16 | 17 | private float mScale; 18 | 19 | private SnowFlake() { 20 | // private 21 | } 22 | 23 | public SnowFlake(Builder builder) { 24 | mPositionX = builder.mPositionX; 25 | mPositionY = builder.mPositionY; 26 | mVelocityY = builder.mVelocityY; 27 | mTransparency = builder.mTransparency; 28 | mScale = builder.mScale; 29 | } 30 | 31 | public float getPositionX() { 32 | return mPositionX; 33 | } 34 | 35 | public void setPositionX(float positionX) { 36 | mPositionX = positionX; 37 | } 38 | 39 | public float getPositionY() { 40 | return mPositionY; 41 | } 42 | 43 | public void setPositionY(float positionY) { 44 | mPositionY = positionY; 45 | } 46 | 47 | public float getVelocityY() { 48 | return mVelocityY; 49 | } 50 | 51 | public void setVelocityY(float velocityY) { 52 | mVelocityY = velocityY; 53 | } 54 | 55 | public int getTransparency() { 56 | return mTransparency; 57 | } 58 | 59 | public void setTransparency(int transparency) { 60 | mTransparency = transparency; 61 | } 62 | 63 | public float getScale() { 64 | return mScale; 65 | } 66 | 67 | public void setScale(float scale) { 68 | mScale = scale; 69 | } 70 | 71 | public static class Builder { 72 | 73 | private float mPositionX; 74 | 75 | private float mPositionY; 76 | 77 | private float mVelocityY; 78 | 79 | private int mTransparency; 80 | 81 | private float mScale; 82 | 83 | public Builder setPositionX(float positionX) { 84 | mPositionX = positionX; 85 | return this; 86 | } 87 | 88 | public Builder setPositionY(float positionY) { 89 | mPositionY = positionY; 90 | return this; 91 | } 92 | 93 | public Builder setVelocityY(float velocityY) { 94 | mVelocityY = velocityY; 95 | return this; 96 | } 97 | 98 | public Builder setTransparency(int transparency) { 99 | mTransparency = transparency; 100 | return this; 101 | } 102 | 103 | public Builder setScale(float scale) { 104 | mScale = scale; 105 | return this; 106 | } 107 | 108 | public SnowFlake create() { 109 | return new SnowFlake(this); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /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 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 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 Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /snowingview/src/main/java/info/hellovass/snowingview/widgets/SnowingView.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.widgets; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.graphics.Bitmap; 6 | import android.graphics.BitmapFactory; 7 | import android.graphics.Canvas; 8 | import android.graphics.Matrix; 9 | import android.graphics.Paint; 10 | import android.hardware.Sensor; 11 | import android.hardware.SensorEvent; 12 | import android.hardware.SensorEventListener; 13 | import android.hardware.SensorManager; 14 | import android.os.Build; 15 | import android.os.Handler; 16 | import android.os.HandlerThread; 17 | import android.os.Message; 18 | import android.support.annotation.RequiresApi; 19 | import android.util.AttributeSet; 20 | import android.view.View; 21 | import info.hellovass.snowingview.R; 22 | import info.hellovass.snowingview.utils.DensityUtil; 23 | import info.hellovass.snowingview.utils.RandomUtil; 24 | 25 | /** 26 | * Created by hellovass on 16/9/26. 27 | * 28 | * winter is coming... 29 | */ 30 | 31 | public class SnowingView extends View implements SensorEventListener { 32 | 33 | private static final String TAG = SnowingView.class.getSimpleName(); 34 | 35 | private final static long INVALID_TIME = -1; 36 | 37 | private final static int MSG_CALCULATE = 233; 38 | 39 | private final static int DEFAULT_SNOWFLAKE_BITMAP_VALUE = -1; 40 | 41 | private final static int DEFAULT_SNOWFLAKE_COUNT = 20; 42 | 43 | private final static int LOW_VELOCITY_Y = 150; 44 | 45 | private final static int HIGH_VELOCITY_Y = 2 * LOW_VELOCITY_Y; 46 | 47 | private final static float GRAVITATIONAL_ACCELERATION = 9.81F; 48 | 49 | private final static float MIN_OFFSET_X = 15.0F; 50 | 51 | private final static float MAX_OFFSET_X = 20.0F; 52 | 53 | private Context mContext; 54 | 55 | private int mWidth; 56 | 57 | private int mHeight; 58 | 59 | private float mSnowFlakeBitmapPivotX; 60 | 61 | private float mSnowFlakeBitmapPivotY; 62 | 63 | private Bitmap mSnowFlakeBitmap; 64 | 65 | private long mLastTimeMillis = INVALID_TIME; 66 | 67 | private Matrix mSnowFlakeMatrix; 68 | 69 | private Paint mSnowFlakePaint; 70 | 71 | private SnowFlake[] mSnowFlakes; 72 | 73 | private HandlerThread mCalculatePositionThread; 74 | 75 | private Handler mCalculateHandler; 76 | 77 | private boolean mIsSnowing = false; 78 | 79 | private SensorManager mSensorManager; 80 | 81 | private Sensor mAccelerometerSensor; 82 | 83 | private float mAccelerationXPercentage; 84 | 85 | public SnowingView(Context context) { 86 | super(context); 87 | init(context, null); 88 | } 89 | 90 | public SnowingView(Context context, AttributeSet attrs) { 91 | super(context, attrs); 92 | init(context, attrs); 93 | } 94 | 95 | public SnowingView(Context context, AttributeSet attrs, int defStyleAttr) { 96 | super(context, attrs, defStyleAttr); 97 | init(context, attrs); 98 | } 99 | 100 | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) 101 | public SnowingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 102 | super(context, attrs, defStyleAttr, defStyleRes); 103 | init(context, attrs); 104 | } 105 | 106 | @Override protected void onDetachedFromWindow() { 107 | super.onDetachedFromWindow(); 108 | mSensorManager.unregisterListener(this); 109 | notifyCalculateThreadStop(); 110 | mCalculatePositionThread.quit(); 111 | } 112 | 113 | /** 114 | * 开始下雪动画 115 | */ 116 | public void startFall() { 117 | mIsSnowing = true; 118 | setVisibility(VISIBLE); 119 | mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_GAME); 120 | } 121 | 122 | /** 123 | * 停止下雪动画 124 | */ 125 | public void stopFall() { 126 | mIsSnowing = false; 127 | setVisibility(GONE); 128 | notifyCalculateThreadStop(); 129 | mSensorManager.unregisterListener(this); 130 | } 131 | 132 | /** 133 | * 是否正在下雪 134 | * 135 | * @return true表示正在下雪 136 | */ 137 | public boolean isSnowing() { 138 | return mIsSnowing; 139 | } 140 | 141 | /** 142 | * 加速度改变时会回调这个方法 143 | */ 144 | @Override public void onSensorChanged(SensorEvent event) { 145 | float accelerationX = event.values[SensorManager.DATA_X]; 146 | mAccelerationXPercentage = accelerationX / GRAVITATIONAL_ACCELERATION; 147 | } 148 | 149 | @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { 150 | 151 | } 152 | 153 | private void init(Context context, AttributeSet attrs) { 154 | 155 | TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SnowingView); 156 | applyAttrsFromXML(array); 157 | array.recycle(); 158 | 159 | mContext = context; 160 | initSensorManager(); 161 | initCalculateThread(); 162 | initCalculateHandler(); 163 | initSnowFlakeMatrix(); 164 | initSnowFlakePaint(); 165 | } 166 | 167 | @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 168 | super.onMeasure(widthMeasureSpec, heightMeasureSpec); 169 | 170 | mWidth = getMeasuredWidth(); 171 | mHeight = getMeasuredHeight(); 172 | 173 | createSnowFlakes(); 174 | } 175 | 176 | @Override protected void onDraw(Canvas canvas) { 177 | super.onDraw(canvas); 178 | 179 | for (SnowFlake snowFlake : mSnowFlakes) { 180 | mSnowFlakeMatrix.setTranslate(0, 0); 181 | mSnowFlakeMatrix.postScale(snowFlake.getScale(), snowFlake.getScale(), mSnowFlakeBitmapPivotX, 182 | mSnowFlakeBitmapPivotY); 183 | mSnowFlakeMatrix.postTranslate(snowFlake.getPositionX(), snowFlake.getPositionY()); 184 | mSnowFlakePaint.setColor(snowFlake.getTransparency()); 185 | canvas.drawBitmap(mSnowFlakeBitmap, mSnowFlakeMatrix, mSnowFlakePaint); 186 | } 187 | 188 | mCalculateHandler.sendEmptyMessage(MSG_CALCULATE); 189 | } 190 | 191 | /** 192 | * 从XML文件中读取自定义的字段并赋值给成员 193 | * 194 | * @param array TypedArray 195 | */ 196 | private void applyAttrsFromXML(TypedArray array) { 197 | mSnowFlakeBitmap = BitmapFactory.decodeResource(getResources(), 198 | array.getResourceId(R.styleable.SnowingView_src, DEFAULT_SNOWFLAKE_BITMAP_VALUE)); 199 | mSnowFlakeBitmapPivotX = mSnowFlakeBitmap.getWidth() / 2.0F; 200 | mSnowFlakeBitmapPivotY = mSnowFlakeBitmap.getHeight() / 2.0F; 201 | } 202 | 203 | /** 204 | * 初始化传感器 205 | */ 206 | private void initSensorManager() { 207 | 208 | if (isInEditMode()) { 209 | return; 210 | } 211 | 212 | mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); 213 | mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 214 | } 215 | 216 | /** 217 | * 初始化工作线程 218 | */ 219 | private void initCalculateThread() { 220 | mCalculatePositionThread = new HandlerThread("calculate_thread"); 221 | mCalculatePositionThread.start(); 222 | } 223 | 224 | /** 225 | * 初始化Handler 226 | */ 227 | private void initCalculateHandler() { 228 | 229 | mCalculateHandler = new Handler(mCalculatePositionThread.getLooper()) { 230 | 231 | @Override public void handleMessage(Message msg) { 232 | super.handleMessage(msg); 233 | 234 | long currentTimeMillis = System.currentTimeMillis(); 235 | 236 | if (mLastTimeMillis != INVALID_TIME) { 237 | 238 | float deltaTime = (currentTimeMillis - mLastTimeMillis) / 1000.0F; 239 | 240 | for (SnowFlake snowFlake : mSnowFlakes) { 241 | 242 | float x = snowFlake.getPositionX() + randomOffsetX(); 243 | float y = snowFlake.getPositionY() + snowFlake.getVelocityY() * deltaTime; 244 | 245 | snowFlake.setPositionX(x); 246 | snowFlake.setPositionY(y); 247 | 248 | if (outOfRange(x, y)) { 249 | snowFlake.setPositionX(randomPositionX()); 250 | snowFlake.setPositionY(resetPositionY()); 251 | } 252 | } 253 | } 254 | 255 | mLastTimeMillis = currentTimeMillis; 256 | postInvalidate(); 257 | } 258 | }; 259 | } 260 | 261 | /** 262 | * 通知HandlerThread停止执行 263 | */ 264 | private void notifyCalculateThreadStop() { 265 | mCalculateHandler.removeMessages(MSG_CALCULATE); 266 | } 267 | 268 | /** 269 | * 初始化雪花矩阵 270 | */ 271 | private void initSnowFlakeMatrix() { 272 | mSnowFlakeMatrix = new Matrix(); 273 | } 274 | 275 | /** 276 | * 初始化雪花画笔 277 | */ 278 | private void initSnowFlakePaint() { 279 | mSnowFlakePaint = new Paint(Paint.ANTI_ALIAS_FLAG); 280 | } 281 | 282 | /** 283 | * 创建雪花数组 284 | */ 285 | private void createSnowFlakes() { 286 | 287 | mSnowFlakes = new SnowFlake[DEFAULT_SNOWFLAKE_COUNT]; 288 | 289 | for (int index = 0; index < mSnowFlakes.length; index++) { 290 | 291 | SnowFlake snowFlake = new SnowFlake.Builder().setPositionX(randomPositionX()) 292 | .setPositionY(randomPositionY()) 293 | .setVelocityY(randomVelocityY()) 294 | .setTransparency(randomTransparency()) 295 | .setScale(randomScale()) 296 | .create(); 297 | 298 | mSnowFlakes[index] = snowFlake; 299 | } 300 | } 301 | 302 | /** 303 | * 随机可能的X坐标 304 | * 305 | * @return 雪花的X坐标 306 | */ 307 | private float randomPositionX() { 308 | return RandomUtil.nextFloat(mWidth + 2 * mSnowFlakeBitmap.getWidth()) 309 | - mSnowFlakeBitmap.getWidth(); 310 | } 311 | 312 | /** 313 | * 随机可能的Y坐标 314 | * 315 | * @return 雪花的Y坐标 316 | */ 317 | private float randomPositionY() { 318 | return RandomUtil.nextFloat(mHeight + 2 * mSnowFlakeBitmap.getHeight()) 319 | - mSnowFlakeBitmap.getHeight(); 320 | } 321 | 322 | /** 323 | * 将雪花的Y坐标重置 324 | * 325 | * @return 雪花的Y坐标 326 | */ 327 | private float resetPositionY() { 328 | return -mSnowFlakeBitmap.getHeight(); 329 | } 330 | 331 | /** 332 | * 随机雪花在Y轴方向上的速度(2dp/s-4dp/s) 333 | * 334 | * @return y轴方向上的速度 335 | */ 336 | private float randomVelocityY() { 337 | 338 | return RandomUtil.nextFloat(DensityUtil.dip2px(mContext, LOW_VELOCITY_Y), 339 | DensityUtil.dip2px(mContext, HIGH_VELOCITY_Y)); 340 | } 341 | 342 | /** 343 | * 随机雪花的透明度 344 | * 345 | * @return 雪花的透明度 346 | */ 347 | private int randomTransparency() { 348 | return RandomUtil.nextInt(10, 255) << 24; 349 | } 350 | 351 | /** 352 | * 随机雪花的缩放比例 353 | * 354 | * @return 雪花的缩放比 355 | */ 356 | private float randomScale() { 357 | return RandomUtil.nextFloat(0.5F, 2.0F); 358 | } 359 | 360 | /** 361 | * 随机X轴的偏移量 362 | * 363 | * @return x轴上的偏移量 364 | */ 365 | private float randomOffsetX() { 366 | return RandomUtil.nextFloat(DensityUtil.dip2px(mContext, MIN_OFFSET_X), 367 | DensityUtil.dip2px(mContext, MAX_OFFSET_X)) * -mAccelerationXPercentage; 368 | } 369 | 370 | /** 371 | * 是否超出View的范围 372 | * 373 | * @return true表示超出范围 374 | */ 375 | private boolean outOfRange(float x, float y) { 376 | 377 | if (x < -mSnowFlakeBitmap.getWidth() || x > mWidth + mSnowFlakeBitmap.getWidth()) { 378 | return true; 379 | } 380 | 381 | if (y > mHeight + mSnowFlakeBitmap.getHeight()) { 382 | return true; 383 | } 384 | 385 | return false; 386 | } 387 | } 388 | -------------------------------------------------------------------------------- /snowingview/src/main/java/info/hellovass/snowingview/widgets/SnowingSurfaceView.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.widgets; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.graphics.Bitmap; 6 | import android.graphics.BitmapFactory; 7 | import android.graphics.Canvas; 8 | import android.graphics.Color; 9 | import android.graphics.Matrix; 10 | import android.graphics.Paint; 11 | import android.hardware.Sensor; 12 | import android.hardware.SensorEvent; 13 | import android.hardware.SensorEventListener; 14 | import android.hardware.SensorManager; 15 | import android.os.Handler; 16 | import android.os.HandlerThread; 17 | import android.os.Message; 18 | import android.util.AttributeSet; 19 | import android.view.SurfaceHolder; 20 | import android.view.SurfaceView; 21 | 22 | import java.util.concurrent.TimeUnit; 23 | 24 | import info.hellovass.snowingview.R; 25 | import info.hellovass.snowingview.utils.DensityUtil; 26 | import info.hellovass.snowingview.utils.RandomUtil; 27 | import rx.Observable; 28 | import rx.Subscription; 29 | import rx.functions.Action1; 30 | import rx.subscriptions.Subscriptions; 31 | 32 | /** 33 | * 作者: 巴掌 on 16/9/30 13:06 34 | * Github: https://github.com/JeasonWong 35 | */ 36 | 37 | public class SnowingSurfaceView extends SurfaceView implements SurfaceHolder.Callback, SensorEventListener { 38 | 39 | Subscription mLooper = Subscriptions.empty(); 40 | 41 | private final static long INVALID_TIME = -1; 42 | 43 | private final static int DEFAULT_SNOWFLAKE_BITMAP_VALUE = -1; 44 | 45 | private final static int DEFAULT_SNOWFLAKE_COUNT = 50; 46 | 47 | private final static int MSG_CALCULATE = 233; 48 | 49 | private final static int LOW_VELOCITY_Y = 150; 50 | 51 | private final static int HIGH_VELOCITY_Y = 2 * LOW_VELOCITY_Y; 52 | 53 | private final static float GRAVITATIONAL_ACCELERATION = 9.81F; 54 | 55 | private final static float MIN_OFFSET_X = 15.0F; 56 | 57 | private final static float MAX_OFFSET_X = 20.0F; 58 | 59 | private int mWidth; 60 | 61 | private int mHeight; 62 | 63 | private HandlerThread mCalculatePositionThread; 64 | 65 | private Handler mCalculateHandler; 66 | 67 | private float mSnowFlakeBitmapPivotX; 68 | 69 | private float mSnowFlakeBitmapPivotY; 70 | 71 | private Bitmap mSnowFlakeBitmap; 72 | 73 | private long mLastTimeMillis = INVALID_TIME; 74 | 75 | private Matrix mSnowFlakeMatrix; 76 | 77 | private Paint mSnowFlakePaint; 78 | 79 | private SnowFlake[] mSnowFlakes; 80 | 81 | private SensorManager mSensorManager; 82 | 83 | private Sensor mAccelerometerSensor; 84 | 85 | private float mAccelerationXPercentage; 86 | 87 | private int mLowVelocityY; 88 | private int mHighVelocityY; 89 | private int mMinOffsetY; 90 | private int mMaxOffsetY; 91 | 92 | private SurfaceHolder mHolder; 93 | 94 | public SnowingSurfaceView(Context context, AttributeSet attrs) { 95 | this(context, attrs, 0); 96 | } 97 | 98 | public SnowingSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) { 99 | super(context, attrs, defStyleAttr); 100 | initView(attrs); 101 | } 102 | 103 | @Override 104 | public void surfaceCreated(SurfaceHolder holder) { 105 | 106 | } 107 | 108 | @Override 109 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 110 | mWidth = getMeasuredWidth(); 111 | mHeight = getMeasuredHeight(); 112 | createSnowFlakes(); 113 | draw(); 114 | } 115 | 116 | @Override 117 | public void surfaceDestroyed(SurfaceHolder holder) { 118 | stopFall(); 119 | } 120 | 121 | private void draw() { 122 | 123 | Canvas canvas = null; 124 | try { 125 | canvas = mHolder.lockCanvas(); 126 | if (canvas != null) { 127 | 128 | canvas.drawColor(Color.BLACK); 129 | 130 | for (SnowFlake snowFlake : mSnowFlakes) { 131 | mSnowFlakeMatrix.setTranslate(0, 0); 132 | mSnowFlakeMatrix.postScale(snowFlake.getScale(), snowFlake.getScale(), mSnowFlakeBitmapPivotX, 133 | mSnowFlakeBitmapPivotY); 134 | mSnowFlakeMatrix.postTranslate(snowFlake.getPositionX(), snowFlake.getPositionY()); 135 | mSnowFlakePaint.setColor(snowFlake.getTransparency()); 136 | canvas.drawBitmap(mSnowFlakeBitmap, mSnowFlakeMatrix, mSnowFlakePaint); 137 | } 138 | 139 | mCalculateHandler.sendEmptyMessage(MSG_CALCULATE); 140 | 141 | } 142 | } finally { 143 | if (canvas != null) { 144 | mHolder.unlockCanvasAndPost(canvas); 145 | } 146 | } 147 | 148 | } 149 | 150 | private void initView(AttributeSet attrs) { 151 | 152 | TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.SnowingView); 153 | applyAttrsFromXML(array); 154 | array.recycle(); 155 | 156 | initSensorManager(); 157 | initCalculateThread(); 158 | initCalculateHandler(); 159 | initSnowFlakeMatrix(); 160 | initSnowFlakePaint(); 161 | 162 | mLowVelocityY = DensityUtil.dip2px(getContext(), LOW_VELOCITY_Y); 163 | mHighVelocityY = DensityUtil.dip2px(getContext(), HIGH_VELOCITY_Y); 164 | mMinOffsetY = DensityUtil.dip2px(getContext(), MIN_OFFSET_X); 165 | mMaxOffsetY = DensityUtil.dip2px(getContext(), MAX_OFFSET_X); 166 | 167 | mHolder = getHolder(); 168 | mHolder.addCallback(this); 169 | } 170 | 171 | /** 172 | * 从XML文件中读取自定义的字段并赋值给成员 173 | * 174 | * @param array TypedArray 175 | */ 176 | private void applyAttrsFromXML(TypedArray array) { 177 | mSnowFlakeBitmap = BitmapFactory.decodeResource(getResources(), 178 | array.getResourceId(R.styleable.SnowingView_src, DEFAULT_SNOWFLAKE_BITMAP_VALUE)); 179 | mSnowFlakeBitmapPivotX = mSnowFlakeBitmap.getWidth() / 2.0F; 180 | mSnowFlakeBitmapPivotY = mSnowFlakeBitmap.getHeight() / 2.0F; 181 | } 182 | 183 | /** 184 | * 初始化传感器 185 | */ 186 | private void initSensorManager() { 187 | 188 | if (isInEditMode()) { 189 | return; 190 | } 191 | 192 | mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE); 193 | mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 194 | } 195 | 196 | /** 197 | * 初始化雪花矩阵 198 | */ 199 | private void initSnowFlakeMatrix() { 200 | mSnowFlakeMatrix = new Matrix(); 201 | } 202 | 203 | /** 204 | * 初始化雪花画笔 205 | */ 206 | private void initSnowFlakePaint() { 207 | mSnowFlakePaint = new Paint(Paint.ANTI_ALIAS_FLAG); 208 | } 209 | 210 | /** 211 | * 初始化工作线程 212 | */ 213 | private void initCalculateThread() { 214 | mCalculatePositionThread = new HandlerThread("calculate_thread"); 215 | mCalculatePositionThread.start(); 216 | } 217 | 218 | /** 219 | * 初始化Handler 220 | */ 221 | private void initCalculateHandler() { 222 | 223 | mCalculateHandler = new Handler(mCalculatePositionThread.getLooper()) { 224 | 225 | @Override 226 | public void handleMessage(Message msg) { 227 | super.handleMessage(msg); 228 | 229 | long currentTimeMillis = System.currentTimeMillis(); 230 | 231 | if (mLastTimeMillis != INVALID_TIME) { 232 | 233 | float deltaTime = (currentTimeMillis - mLastTimeMillis) / 1000.0F; 234 | 235 | for (SnowFlake snowFlake : mSnowFlakes) { 236 | 237 | float x = snowFlake.getPositionX() + randomOffsetX(); 238 | float y = snowFlake.getPositionY() + snowFlake.getVelocityY() * deltaTime; 239 | 240 | if (outOfRange(x, y)) { 241 | snowFlake.setPositionX(randomPositionX()); 242 | snowFlake.setPositionY(resetPositionY()); 243 | } else { 244 | snowFlake.setPositionX(x); 245 | snowFlake.setPositionY(y); 246 | } 247 | } 248 | } 249 | 250 | mLastTimeMillis = currentTimeMillis; 251 | } 252 | }; 253 | } 254 | 255 | /** 256 | * 创建雪花数组 257 | */ 258 | private void createSnowFlakes() { 259 | 260 | mSnowFlakes = new SnowFlake[DEFAULT_SNOWFLAKE_COUNT]; 261 | 262 | for (int index = 0; index < mSnowFlakes.length; index++) { 263 | 264 | SnowFlake snowFlake = new SnowFlake.Builder().setPositionX(randomPositionX()) 265 | .setPositionY(randomPositionY()) 266 | .setVelocityY(randomVelocityY()) 267 | .setTransparency(randomTransparency()) 268 | .setScale(randomScale()) 269 | .create(); 270 | 271 | mSnowFlakes[index] = snowFlake; 272 | } 273 | } 274 | 275 | /** 276 | * 随机可能的X坐标 277 | * 278 | * @return 雪花的X坐标 279 | */ 280 | private float randomPositionX() { 281 | return RandomUtil.nextFloat(mWidth + 2 * mSnowFlakeBitmap.getWidth()) 282 | - mSnowFlakeBitmap.getWidth(); 283 | } 284 | 285 | /** 286 | * 随机可能的Y坐标 287 | * 288 | * @return 雪花的Y坐标 289 | */ 290 | private float randomPositionY() { 291 | return RandomUtil.nextFloat(mHeight + 2 * mSnowFlakeBitmap.getHeight()) 292 | - mSnowFlakeBitmap.getHeight(); 293 | } 294 | 295 | /** 296 | * 将雪花的Y坐标重置 297 | * 298 | * @return 雪花的Y坐标 299 | */ 300 | private float resetPositionY() { 301 | return -mSnowFlakeBitmap.getHeight(); 302 | } 303 | 304 | /** 305 | * 随机雪花在Y轴方向上的速度(2dp/s-4dp/s) 306 | * 307 | * @return y轴方向上的速度 308 | */ 309 | private float randomVelocityY() { 310 | 311 | return RandomUtil.nextFloat(mLowVelocityY, mHighVelocityY); 312 | } 313 | 314 | /** 315 | * 随机雪花的透明度 316 | * 317 | * @return 雪花的透明度 318 | */ 319 | private int randomTransparency() { 320 | return RandomUtil.nextInt(10, 255) << 24; 321 | } 322 | 323 | /** 324 | * 随机雪花的缩放比例 325 | * 326 | * @return 雪花的缩放比 327 | */ 328 | private float randomScale() { 329 | return RandomUtil.nextFloat(0.5F, 2.0F); 330 | } 331 | 332 | /** 333 | * 随机X轴的偏移量 334 | * 335 | * @return x轴上的偏移量 336 | */ 337 | private float randomOffsetX() { 338 | return RandomUtil.nextFloat(mMinOffsetY, mMaxOffsetY) * -mAccelerationXPercentage; 339 | } 340 | 341 | /** 342 | * 是否超出View的范围 343 | * 344 | * @return true表示超出范围 345 | */ 346 | private boolean outOfRange(float x, float y) { 347 | 348 | if (x < -mSnowFlakeBitmap.getWidth() || x > mWidth + mSnowFlakeBitmap.getWidth()) { 349 | return true; 350 | } 351 | 352 | if (y > mHeight + mSnowFlakeBitmap.getHeight()) { 353 | return true; 354 | } 355 | 356 | return false; 357 | } 358 | 359 | @Override 360 | public void onSensorChanged(SensorEvent event) { 361 | float accelerationX = event.values[SensorManager.DATA_X]; 362 | mAccelerationXPercentage = accelerationX / GRAVITATIONAL_ACCELERATION; 363 | } 364 | 365 | @Override 366 | public void onAccuracyChanged(Sensor sensor, int accuracy) { 367 | 368 | } 369 | 370 | /** 371 | * 通知HandlerThread停止执行 372 | */ 373 | private void notifyCalculateThreadStop() { 374 | mCalculateHandler.removeMessages(MSG_CALCULATE); 375 | } 376 | 377 | private void startLooper() { 378 | mLooper.unsubscribe(); 379 | mLooper = Observable.interval(1, TimeUnit.MILLISECONDS) 380 | .subscribe(new Action1() { 381 | @Override 382 | public void call(Long aLong) { 383 | draw(); 384 | } 385 | }); 386 | } 387 | 388 | private void stopLooper() { 389 | mLooper.unsubscribe(); 390 | } 391 | 392 | /** 393 | * 开始下雪动画 394 | */ 395 | public void startFall() { 396 | setVisibility(VISIBLE); 397 | mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_GAME); 398 | startLooper(); 399 | } 400 | 401 | /** 402 | * 停止下雪动画 403 | */ 404 | public void stopFall() { 405 | setVisibility(GONE); 406 | mSensorManager.unregisterListener(this); 407 | notifyCalculateThreadStop(); 408 | stopLooper(); 409 | } 410 | 411 | @Override 412 | protected void onDetachedFromWindow() { 413 | super.onDetachedFromWindow(); 414 | stopFall(); 415 | mCalculatePositionThread.quit(); 416 | } 417 | 418 | } 419 | -------------------------------------------------------------------------------- /snowingview/src/main/java/info/hellovass/snowingview/widgets/SnowingPaperService.java: -------------------------------------------------------------------------------- 1 | package info.hellovass.snowingview.widgets; 2 | 3 | import android.content.Context; 4 | import android.graphics.Bitmap; 5 | import android.graphics.BitmapFactory; 6 | import android.graphics.Canvas; 7 | import android.graphics.Color; 8 | import android.graphics.Matrix; 9 | import android.graphics.Paint; 10 | import android.hardware.Sensor; 11 | import android.hardware.SensorEvent; 12 | import android.hardware.SensorEventListener; 13 | import android.hardware.SensorManager; 14 | import android.os.Handler; 15 | import android.os.HandlerThread; 16 | import android.os.Message; 17 | import android.service.wallpaper.WallpaperService; 18 | import android.view.SurfaceHolder; 19 | 20 | import java.util.concurrent.TimeUnit; 21 | 22 | import info.hellovass.snowingview.R; 23 | import info.hellovass.snowingview.utils.DensityUtil; 24 | import info.hellovass.snowingview.utils.RandomUtil; 25 | import rx.Observable; 26 | import rx.Subscription; 27 | import rx.functions.Action1; 28 | import rx.subscriptions.Subscriptions; 29 | 30 | /** 31 | * 作者: 巴掌 on 16/9/30 13:41 32 | * Github: https://github.com/JeasonWong 33 | */ 34 | 35 | public class SnowingPaperService extends WallpaperService { 36 | 37 | @Override 38 | public Engine onCreateEngine() { 39 | return new SnowingEngine(); 40 | } 41 | 42 | public class SnowingEngine extends Engine implements SensorEventListener { 43 | 44 | Subscription mLooper = Subscriptions.empty(); 45 | 46 | private boolean isVisible; 47 | 48 | private final static long INVALID_TIME = -1; 49 | 50 | private final static int DEFAULT_SNOWFLAKE_COUNT = 10; 51 | 52 | private final static int MSG_CALCULATE = 233; 53 | 54 | private final static int LOW_VELOCITY_Y = 150; 55 | 56 | private final static int HIGH_VELOCITY_Y = 2 * LOW_VELOCITY_Y; 57 | 58 | private final static float GRAVITATIONAL_ACCELERATION = 9.81F; 59 | 60 | private final static float MIN_OFFSET_X = 15.0F; 61 | 62 | private final static float MAX_OFFSET_X = 20.0F; 63 | 64 | private Context mContext; 65 | 66 | private int mWidth; 67 | 68 | private int mHeight; 69 | 70 | private HandlerThread mCalculatePositionThread; 71 | 72 | private Handler mCalculateHandler; 73 | 74 | private float mSnowFlakeBitmapPivotX; 75 | 76 | private float mSnowFlakeBitmapPivotY; 77 | 78 | private Bitmap mSnowFlakeBitmap; 79 | 80 | private long mLastTimeMillis = INVALID_TIME; 81 | 82 | private Matrix mSnowFlakeMatrix; 83 | 84 | private Paint mSnowFlakePaint; 85 | 86 | private SnowFlake[] mSnowFlakes; 87 | 88 | private SensorManager mSensorManager; 89 | 90 | private Sensor mAccelerometerSensor; 91 | 92 | private float mAccelerationXPercentage; 93 | 94 | private int mLowVelocityY; 95 | private int mHighVelocityY; 96 | private int mMinOffsetY; 97 | private int mMaxOffsetY; 98 | 99 | private SurfaceHolder mHolder; 100 | 101 | public SnowingEngine() { 102 | super(); 103 | mContext = getApplicationContext(); 104 | mHolder = getSurfaceHolder(); 105 | mSnowFlakeBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_snowflake); 106 | mSnowFlakeBitmapPivotX = mSnowFlakeBitmap.getWidth() / 2.0F; 107 | mSnowFlakeBitmapPivotY = mSnowFlakeBitmap.getHeight() / 2.0F; 108 | mLowVelocityY = DensityUtil.dip2px(mContext, LOW_VELOCITY_Y); 109 | mHighVelocityY = DensityUtil.dip2px(mContext, HIGH_VELOCITY_Y); 110 | mMinOffsetY = DensityUtil.dip2px(mContext, MIN_OFFSET_X); 111 | mMaxOffsetY = DensityUtil.dip2px(mContext, MAX_OFFSET_X); 112 | initSensorManager(); 113 | initCalculateThread(); 114 | initCalculateHandler(); 115 | initSnowFlakeMatrix(); 116 | initSnowFlakePaint(); 117 | 118 | } 119 | 120 | @Override 121 | public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) { 122 | super.onSurfaceChanged(holder, format, width, height); 123 | mWidth = width; 124 | mHeight = height; 125 | createSnowFlakes(); 126 | } 127 | 128 | @Override 129 | public void onVisibilityChanged(boolean visible) { 130 | super.onVisibilityChanged(visible); 131 | isVisible = visible; 132 | if (visible) { 133 | startFall(); 134 | } else { 135 | stopFall(); 136 | } 137 | } 138 | 139 | @Override 140 | public void onSurfaceDestroyed(SurfaceHolder holder) { 141 | super.onSurfaceDestroyed(holder); 142 | stopFall(); 143 | } 144 | 145 | /** 146 | * 初始化传感器 147 | */ 148 | private void initSensorManager() { 149 | mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); 150 | mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 151 | } 152 | 153 | /** 154 | * 初始化雪花矩阵 155 | */ 156 | private void initSnowFlakeMatrix() { 157 | mSnowFlakeMatrix = new Matrix(); 158 | } 159 | 160 | /** 161 | * 初始化雪花画笔 162 | */ 163 | private void initSnowFlakePaint() { 164 | mSnowFlakePaint = new Paint(Paint.ANTI_ALIAS_FLAG); 165 | } 166 | 167 | /** 168 | * 初始化工作线程 169 | */ 170 | private void initCalculateThread() { 171 | mCalculatePositionThread = new HandlerThread("calculate_thread"); 172 | mCalculatePositionThread.start(); 173 | } 174 | 175 | /** 176 | * 初始化Handler 177 | */ 178 | private void initCalculateHandler() { 179 | 180 | mCalculateHandler = new Handler(mCalculatePositionThread.getLooper()) { 181 | 182 | @Override 183 | public void handleMessage(Message msg) { 184 | super.handleMessage(msg); 185 | 186 | long currentTimeMillis = System.currentTimeMillis(); 187 | 188 | if (mLastTimeMillis != INVALID_TIME) { 189 | 190 | float deltaTime = (currentTimeMillis - mLastTimeMillis) / 1000.0F; 191 | 192 | for (SnowFlake snowFlake : mSnowFlakes) { 193 | 194 | float x = snowFlake.getPositionX() + randomOffsetX(); 195 | float y = snowFlake.getPositionY() + snowFlake.getVelocityY() * deltaTime; 196 | 197 | if (outOfRange(x, y)) { 198 | snowFlake.setPositionX(randomPositionX()); 199 | snowFlake.setPositionY(resetPositionY()); 200 | } else { 201 | snowFlake.setPositionX(x); 202 | snowFlake.setPositionY(y); 203 | } 204 | } 205 | } 206 | 207 | mLastTimeMillis = currentTimeMillis; 208 | } 209 | }; 210 | } 211 | 212 | /** 213 | * 创建雪花数组 214 | */ 215 | private void createSnowFlakes() { 216 | 217 | mSnowFlakes = new SnowFlake[DEFAULT_SNOWFLAKE_COUNT]; 218 | 219 | for (int index = 0; index < mSnowFlakes.length; index++) { 220 | 221 | SnowFlake snowFlake = new SnowFlake.Builder().setPositionX(randomPositionX()) 222 | .setPositionY(randomPositionY()) 223 | .setVelocityY(randomVelocityY()) 224 | .setTransparency(randomTransparency()) 225 | .setScale(randomScale()) 226 | .create(); 227 | 228 | mSnowFlakes[index] = snowFlake; 229 | } 230 | } 231 | 232 | /** 233 | * 随机可能的X坐标 234 | * 235 | * @return 雪花的X坐标 236 | */ 237 | private float randomPositionX() { 238 | return RandomUtil.nextFloat(mWidth + 2 * mSnowFlakeBitmap.getWidth()) 239 | - mSnowFlakeBitmap.getWidth(); 240 | } 241 | 242 | /** 243 | * 随机可能的Y坐标 244 | * 245 | * @return 雪花的Y坐标 246 | */ 247 | private float randomPositionY() { 248 | return RandomUtil.nextFloat(mHeight + 2 * mSnowFlakeBitmap.getHeight()) 249 | - mSnowFlakeBitmap.getHeight(); 250 | } 251 | 252 | /** 253 | * 将雪花的Y坐标重置 254 | * 255 | * @return 雪花的Y坐标 256 | */ 257 | private float resetPositionY() { 258 | return -mSnowFlakeBitmap.getHeight(); 259 | } 260 | 261 | /** 262 | * 随机雪花在Y轴方向上的速度(2dp/s-4dp/s) 263 | * 264 | * @return y轴方向上的速度 265 | */ 266 | private float randomVelocityY() { 267 | 268 | return RandomUtil.nextFloat(mLowVelocityY, mHighVelocityY); 269 | } 270 | 271 | /** 272 | * 随机雪花的透明度 273 | * 274 | * @return 雪花的透明度 275 | */ 276 | private int randomTransparency() { 277 | return RandomUtil.nextInt(10, 255) << 24; 278 | } 279 | 280 | /** 281 | * 随机雪花的缩放比例 282 | * 283 | * @return 雪花的缩放比 284 | */ 285 | private float randomScale() { 286 | return RandomUtil.nextFloat(0.5F, 2.0F); 287 | } 288 | 289 | /** 290 | * 随机X轴的偏移量 291 | * 292 | * @return x轴上的偏移量 293 | */ 294 | private float randomOffsetX() { 295 | return RandomUtil.nextFloat(mMinOffsetY, mMaxOffsetY) * -mAccelerationXPercentage; 296 | } 297 | 298 | /** 299 | * 是否超出View的范围 300 | * 301 | * @return true表示超出范围 302 | */ 303 | private boolean outOfRange(float x, float y) { 304 | 305 | if (x < -mSnowFlakeBitmap.getWidth() || x > mWidth + mSnowFlakeBitmap.getWidth()) { 306 | return true; 307 | } 308 | 309 | if (y > mHeight + mSnowFlakeBitmap.getHeight()) { 310 | return true; 311 | } 312 | 313 | return false; 314 | } 315 | 316 | private void draw() { 317 | 318 | Canvas canvas = null; 319 | try { 320 | canvas = mHolder.lockCanvas(); 321 | if (canvas != null) { 322 | 323 | canvas.drawColor(Color.BLACK); 324 | 325 | for (SnowFlake snowFlake : mSnowFlakes) { 326 | mSnowFlakeMatrix.setTranslate(0, 0); 327 | mSnowFlakeMatrix.postScale(snowFlake.getScale(), snowFlake.getScale(), mSnowFlakeBitmapPivotX, 328 | mSnowFlakeBitmapPivotY); 329 | mSnowFlakeMatrix.postTranslate(snowFlake.getPositionX(), snowFlake.getPositionY()); 330 | mSnowFlakePaint.setColor(snowFlake.getTransparency()); 331 | canvas.drawBitmap(mSnowFlakeBitmap, mSnowFlakeMatrix, mSnowFlakePaint); 332 | } 333 | 334 | mCalculateHandler.sendEmptyMessage(MSG_CALCULATE); 335 | } 336 | } finally { 337 | if (canvas != null) { 338 | mHolder.unlockCanvasAndPost(canvas); 339 | } 340 | } 341 | 342 | } 343 | 344 | @Override 345 | public void onSensorChanged(SensorEvent event) { 346 | float accelerationX = event.values[SensorManager.DATA_X]; 347 | mAccelerationXPercentage = accelerationX / GRAVITATIONAL_ACCELERATION; 348 | } 349 | 350 | @Override 351 | public void onAccuracyChanged(Sensor sensor, int accuracy) { 352 | 353 | } 354 | 355 | /** 356 | * 通知HandlerThread停止执行 357 | */ 358 | private void notifyCalculateThreadStop() { 359 | mCalculateHandler.removeMessages(MSG_CALCULATE); 360 | } 361 | 362 | private void startLooper() { 363 | mLooper.unsubscribe(); 364 | mLooper = Observable.interval(12, TimeUnit.MILLISECONDS) 365 | .subscribe(new Action1() { 366 | @Override 367 | public void call(Long aLong) { 368 | if (isVisible) { 369 | draw(); 370 | } 371 | } 372 | }); 373 | } 374 | 375 | private void stopLooper() { 376 | mLooper.unsubscribe(); 377 | } 378 | 379 | /** 380 | * 开始下雪动画 381 | */ 382 | public void startFall() { 383 | mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_GAME); 384 | startLooper(); 385 | } 386 | 387 | /** 388 | * 停止下雪动画 389 | */ 390 | public void stopFall() { 391 | mSensorManager.unregisterListener(this); 392 | notifyCalculateThreadStop(); 393 | stopLooper(); 394 | } 395 | 396 | } 397 | 398 | } 399 | --------------------------------------------------------------------------------