在Android應用中實現視差背景效果:ParallaxViewPager

jopen 10年前發布 | 23K 次閱讀 Android Android開發 移動開發

ParallaxViewPager實現Viewpager左右滑動,背景跟隨滾動差移動.

An easy-to-use ViewPager subclass with parallax background.

Setup requires little extra effort, using the ParallaxViewPager is just like using a standard ViewPager, with the same adapter. Of course, there's no silver bullet - the developer has to supply a background tailored to the current needs (eg. the number of items in the adapter and the size of the ViewPager). Check out this gif and this blog post to see what it's all about.

  1. Include it in your project as a Gradle dependency:
  2. </ol>

        dependencies {
            compile 'com.andraskindler.parallaxviewpager:parallaxviewpager:0.3.1'
        }

    1. Create a ParallaxViewPager programmatically or in a layout xml.

      </li>

    2. Set the background via xml or one of the following methods:

      • setBackgroundResource(int resid)
      • setBackground(Drawable background) or setBackgroundDrawable(Drawable background)
      • setBackground(Bitmap bitmap)
      • </ul> </li>

      • (Optional) Specify how the view should scale the background with the setScaleType(final int scaleType) method. Choose from the following parameters:

        • FIT_HEIGHT means the height of the image is resized to matched the height of the View, also stretching the width to keep the aspect ratio. The non-visible part of the bitmap is divided into equal parts, each of them sliding in at the proper position. This is the default value.
        • FIT_WIDTH means the width of the background image is divided into equal chunks, each taking up the whole width of the screen. This mode is not the usual parallax-effect, as the speed of the background scrolling equals the speed of the views.
        • </ul> </li>

        • (Optional) Set the amount of overlapping with the setOverlapPercentage(final float percentage) method. This is a number between 0 and 1, the smaller it is, the slower is the background scrolling. The default value is 50 percent. This only works with FIT_HEIGHT.

          </li> </ol>

          An example, inside the onCreate() of an activity:

              //...
              final ParallaxViewPager parallaxViewPager = new ParallaxViewPager(this);
              parallaxViewPager.setAdapter(new MyPagerAdapter());
              parallaxViewPager.setBackgroundResource(R.drawable.nagy);
              setContentView(parallaxViewPager);
              //...

          項目主頁:http://www.baiduhome.net/lib/view/home/1409304422885

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!