How does one go about creating a View
that has boundaries with triangular perforations ?
I've been using background drawables to achieve this so far. That works when the dimensions of the View
are fixed. Now I have a situation where the height of the View
is not constant, so I need to have the height variable on the fly. I can't use a background drawable with a fixed height anymore.
Here is the original background drawable:
And this is what the final View
needs to look like:
Another way of looking at the same problem is, can we allow the center of the image to stretch without distorting the boundaries ? If we could do this, we could use the existing drawable as a background.
How can this be achieved ? Has anyone else faced this problem before ? Does the framework have an existing way of dealing with this class of problems ?
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 withandroid:src
. Then the middle image specifies the drawable withandroid:background
and resizes to fill the height of the parent layout withandroid:layout_height="match_parent"
andandroid: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.You can use a NinePatch image as drawable of that view. To learn how to create a NinePatch image, goto Draw 9-patch
Instead of using a normal image, you can generate a nine-patch png.
Use
Simple Nine-patch Generator
for this.The trick is the black line on the left side. That tells Android that the png is vertically expandable along this area.
Please see this example:
Save it as a nine-patch, in the format imagename.9.png
You can draw a zigzag path in background of your view
refrence