9-patch Transparency Gotcha

Tutorial By 4 years ago

Recently I had a project design which required borders around each image displayed. To avoid overdraw I used a 9-patch image resource with a transparent center in which the image would be placed. This would theoretically avoiding overdraw completely. So after a quick session in photoshop I knocked a 9-patch, turned on “Show Overdraw” on my dev phone and did a test run.

 

Not quite the results I was hoping for! If you look very carefully, you will notice that while almost everything is blue (good), there is a thin border of green around each image which signifies overdraw. The obvious place the overdraw could have come from is the content patches along to the bottom and right hand side. If they happened to be too long and overlapped the border then overdrawing would occur. A quick examination of the resource proved that was not the issue, the content images were correct.

Given that the content patches were correct, that only left the stretch patches. That raised the question, What if the stretch patches not only told Android where to stretch the image, but also told it where to stop drawing due to transparency. With that question in mind, I set out to test the theory.

After extending the stretch patches across the entire transparency section I fired up the app once again.

 

Success!

 

There you have it, if you’re going to use transparency in 9-patch resources to reduce overdraw be sure that your stretch patches encompass the whole transparent area.

 

If your interested on more tips for UI performance check out Romain Guys post at curious-creature.org