How to programmatically re-apply a 9-patch image to an ImageView?

后端 未结 5 1843
挽巷
挽巷 2020-12-03 23:24

I have an activity that has an ImageView defined inside a HorizontalScrollView. The image source is a 9-patch file that is constrained to stretch only the right edge to fill

相关标签:
5条回答
  • 2020-12-03 23:40

    9-patch images seem to only work when they're set as a View's background image. So:

    • instead of android:src, set android:background in your layout XML, and
    • call setBackgroundResource() when you want to change the image.

    You can also use a plain View instead of an ImageView if you want; it doesn't really matter much.

    0 讨论(0)
  • 2020-12-03 23:42

    Move this: ImageView imgResultMap = (ImageView)findViewById(R.id.imgResultMap); to a global intialized in the onCreate method. Otherwise the device has to search for the view and find it every time it is tapped.

    and try calling imgResultMap.invalidate(); before you return from the onDoubleTap method (http://developer.android.com/reference/android/view/View.html#invalidate())

    0 讨论(0)
  • 2020-12-03 23:46

    EDIT: After doing some research, I have it figured out. Instead of just manipulating the bitmap, I need to also include the 9-patch chunk, which is not part of the bitmap image, to re-construct a new 9-patch drawable. See sample code below:

        ...
     else {
            // Zoom out
            zoom = 1;
            Bitmap mapBitmapScaled = mapBitmap; 
            // Load the 9-patch data chunk and apply to the view
            byte[] chunk = mapBitmap.getNinePatchChunk();
            NinePatchDrawable mapNinePatch = new NinePatchDrawable(getResources(), 
                mapBitmapScaled, chunk, new Rect(), null);
            imgResultMap.setImageDrawable(mapNinePatch);
     }
    
      ....
    

    EDIT #2: For those who looks at my solution here, also take a look at Kai's suggestions below regarding memory management. Very useful information.

    0 讨论(0)
  • 2020-12-03 23:48

    Also another solution is to set image programmatically as ImageResource and set scaleType

    imageView.setImageResource(R.drawable.favorite_driver_icon);
    imageView.setScaleType(ScaleType.FIT_XY);
    
    0 讨论(0)
  • 2020-12-03 23:55

    Why don't you just include two different scaled images and switch between them using imgResultMap.setImageResource(resId) when zooming? Also note that you are loading & creating Bitmaps in UIThread which is not a good way to provide smooth user experience, at least preload the bitmap only once during onCreate() and cache that.

    0 讨论(0)
提交回复
热议问题