Skip to content Skip to sidebar Skip to footer

How To Set 9-patch Background For ViewPager, That Will Put The Pages Inside, And Keep Aspect Ratio?

Background I have a ViewPager (of images pages), which needs to show its content inside an image that should keep its aspect ratio. The problem Problem is, when I just set a 9-patc

Solution 1:

ok, so what I did is this:

  1. set the 9-patch as a background to the parent of the ViewPager, or to the ViewPager itself.
  2. right when you get the size of the view, calculate what should be the width or height of it, depending on the bitmap size and the restrictions you have, and set it to the view.

In my case, the restrictions were to fill it to the height of the parent, so what I needed is to calculate the needed width...

Weird thing, is that I still see artefacts. The bottom of the viewpager has about 1-2 pixels rows of the background instead of being of itself (the "hole" of the 9-patch is at the bottom of the image).

EDIT: fixed it too. Seems to be an issue with various screen pixels-densities. Here's a snippet:

public static void runJustBeforeBeingDrawn(final View view, final Runnable runnable) {
    final OnPreDrawListener preDrawListener = new OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            runnable.run();
            return true;
        }
    };
    view.getViewTreeObserver().addOnPreDrawListener(preDrawListener);
}

public static BitmapFactory.Options getBitmapOptions(final Resources res, final int resId) {
    final BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, bitmapOptions);
    return bitmapOptions;
}


    final Options bitmapOptions = getBitmapOptions(getResources(), R.drawable.nine_patch_image);
    final View viewPagerContainer = ...;
    runJustBeforeBeingDrawn(viewPagerContainer, new Runnable() {
        @Override
        public void run() {
            int neededWidth = (int)Math.ceil((float) bitmapOptions.outWidth * viewPagerContainer.getHeight() / bitmapOptions.outHeight);
            final LayoutParams layoutParams = viewPagerContainer.getLayoutParams();
            layoutParams.width=neededWidth;
            viewPagerContainer.setLayoutParams(layoutParams);
        }
    });

EDIT: Alternative to runJustBeforeBeingDrawn: https://stackoverflow.com/a/28136027/878126


Post a Comment for "How To Set 9-patch Background For ViewPager, That Will Put The Pages Inside, And Keep Aspect Ratio?"