Android nine patch - allow only a specific area of a background drawable to stretch

后端 未结 4 1586
傲寒
傲寒 2021-02-06 15:11

How does one go about creating a View that has boundaries with triangular perforations ?

I\'ve been using background drawables to achieve this so

4条回答
  •  一整个雨季
    2021-02-06 16:02

    The 9 patch mechanism didn't work to do something similar for my use case, because it requires a stretchable region to be defined in both the horizontal and vertical directions. The 9 patch will only work if the ImageView is able to be constrained to the exact width of the source drawables, to avoid any horizontal stretching.

    If the view needs to be allowed to stretch horizontally, maintaining the aspect ratio of the top and bottom boundary portions of the image, while the middle portion is allowed to stretch freely in both directions, a 9 patch won't work for this. I created this layout to accomplish this:

    
    
    
        
    
        
    
        
    
    
    

    image_top.png

    image_middle.png (Note, this image could be shrunk to as little as 1 pixel high, if the subtle gray gradient on the right isn't necessary.)

    image_bottom.png

    The key is having android:adjustViewBounds="true" on the boundary images, while the drawables are specified with android:src. Then the middle image specifies the drawable with android:background and resizes to fill the height of the parent layout with android:layout_height="match_parent" and android:layout_weight="1".

    android:scaleType="fitXY" was necessary in addition in order to force a final scaling of the images after their view bounds are adjusted to handle any potential tiny pixel differences in alignment on hi-res displays. They are all resized to fill their bounds completely.

提交回复
热议问题