A simple guide to 9-patch for Android UI

May 18, 2011
 · 
4 min read

While I was working on my first Android app, I found 9-patch (aka 9.png) to be confusing and poorly documented. After a little while, I finally picked up on how it works and decided to throw together something to help others figure it out.

Basically, 9-patch uses png transparency to do an advanced form of 9-slice or scale9. The guides are straight, 1-pixel black lines drawn on the edge of your image that define the scaling and fill of your image. By naming your image file name.9.png, Android will recognize the 9.png format and use the black guides to scale and fill your bitmaps.

Here's a basic guide map:

As you can see, you have guides on each side of your image. The TOP and LEFT guides are for scaling your image (i.e. 9-slice), while the RIGHT and BOTTOM guides define the fill area.

The black guide lines are cut-off/removed from your image - they won't show in the app.  Guides must only be one pixel wide, so if you want a 48x48 button, your png will actually be 50x50. Anything thicker than one pixel will remain part of your image. (My examples have 4-pixel wide guides for better visibility. They should really be only 1-pixel).

Your guides must be solid black (#000000). Even a slight difference in color (#000001) or alpha will cause it to fail and stretch normally. This failure won't be obvious either*, it fails silently! Yes. Really. Now you know.

Also you should keep in mind that remaining area of the one-pixel outline must be completely transparent. This includes the four corners of the image - those should always be clear. This can be a bigger problem than you realize. For example, if you scale an image in Photoshop it will add anti-aliased pixels which may include almost-invisible pixels which will also cause it to fail*. If you must scale in Photoshop, use the Nearest Neighbor setting in the Resample Image pulldown menu (at the bottom of the Image Size pop-up menu) to keep sharp edges on your guides.

*(updated 1/2012) This is actually a "fix" in the latest dev kit. Previously it would manifest itself as all of your other images and resources suddenly breaking, not the actually broken 9-patch image.

The TOP and LEFT guides are used to define the scalable portion of your image - LEFT for scaling height, TOP for scaling width. Using a button image as an example, this means the button can stretch horizontally and vertically within the black portion and everything else, such as the corners, will remain the same size. The allows you to have buttons that can scale to any size and maintain a uniform look.

It's important to note that 9-patch images don't scale down - they only scale up. So it's best to start as small as possible.

Also, you can leave out portions in the middle of the scale line. So for example, if you have a button with a sharp glossy edge across the middle, you can leave out a few pixels in the middle of the LEFT guide. The center horizontal axis of your image won't scale, just the parts above and below it, so your sharp gloss won't get anti-aliased or fuzzy.

Fill area guides are optional and provide a way define the area for stuff like your text label. Fill determines how much room there is within your image to place text, or an icon, or other things. 9-patch isn't just for buttons, it works for background images as well.

The above button & label example is exaggerated simply to explain the idea of fill - the label isn't completely accurate. To be honest, I haven't experienced how Android does multi-line labels since a button label is usually a single row of text.

Finally, here's a good demonstration of how scale and fill guides can vary, such as a LinearLayout with a background image & fully rounded sides:

With this example, the LEFT guide isn't used but we're still required to have a guide. The background image don't scale vertically; it just scales horizontally (based on the TOP guide). Looking at the fill guides, the RIGHT and BOTTOM guides extend beyond where they meet the image's curved edges. This allows me to place my round buttons close to the edges of the background for a tight, fitted look.

So that's it. 9-patch is super easy, once you get it. It's not a perfect way to do scaling, but the fill-area and multi-line scale-guides does offer more flexibility than traditional 9-slice and scale9. Give it a try and you'll figure it out quickly.

For more useful tips, follow me on Twitter.

Comments
One other thing that I don’t think is documented on the official page, is that you can actually have more than one “stretchable” region on each side. There are a few .9.png files in the SDK that use this.
So imagine you have an icon in the middle of a button that you don’t want to stretch, but you do want the space either side of the icon to stretch… Your top black line would be in 2 parts, either side of the icon.
Radu
Very useful ! Thank you !
Sara
Very helpful! Thanks so much for your article.
Question: Normally Android recommends that you provide multiple versions of each image to account for different screen sizes/resolutions. Is that still required when you use a 9 Patch image? If you only need a single 9 Patch image for all resolutions, which baseline resolution do you pick?
Thanks so much.
radley
There’s about a 30% size difference between mdpi & hdpi so I always do 2x screen images; I do mdpi & hdpi and ignore ldpi. By my understanding, mdpi is the standard baseline for dp scaling: layouts match mdpi and scale from there to hdpi.
David
Great article! :)
However, there’s something I don’t understand: if I don’t use the LEFT guide (because I don’t want the image to be stretched vertically), I get this error message: “No marked region found along edge. – Found along left edge”.
I think I must be missing something, but I can’t figure out what’s wrong.
Thanks a lot!
radley
Nice catch. I checked out my actual working assets and turns out I did use a left guide, even though I’m not scaling vertically.
I’ve updated the graphic and post. Thanks for catching that =)
Thank you for the article.
I have posted a link on my blog: http://android9patch.blogspot.com
Richard.
Charmme
How to use 9 patch image in a android? Where 9 patch tools in Eclipse?
When i use 9 patch image it gave error No resource found?
Plz give proper guideliness.
In adv Thanks.
radley,
Your blog reader and yourself are invited to come grab some free 9 patch PNG on my blog: http://android9patch.blogspot.com
I have a link back to your article here since I really like.
Keep on the good work!
Cheers!
Richard.
Awesome post! Easy to understand – thumbs up.
Jason
This is a fantastic explanation of 9 patch. Thank you for taking the time to create it.
Atli
You rock! Finally I understood, the android documentation is terrible, thanks for putting this out.
wellwisher
Great tutorial.. All my doubts got clarified.. expecting more on different topics..
Gubatron
THANK YOU! I finally understand.
JohnS
Great write-up. Thank you.
unplugged
ho God, thanks for the write up!!
its well explained
[…] Installation Script Syntax's – xda-developers [GUIDE] Want to learn how to theme? – xda-developers A simple guide to 9-patch for Android UI | @radley Enjoy GA_googleFillSlot("PhanForum_1stPostSig_300x250"); __________________ [ROM] CTMod […]
[…] 比较为大众采用一种解决方案是NinePatch。可以毫不夸张得说,9 patch是Android中解决自适应问题的利器。介绍和使用你可以看看这里还有这里。 […]
Nice post! Very easy to understand – thanks.
[…] liegt der absturz auch daran, weil es sich um 9-files handelt… Draw 9-patch | Android Developers A simple guide to 9-patch for Android UI | @radley Android 9 […]
[…] Image source and more information: http://radleymarx.com/blog/simple-guide-to-9-patch/ […]
Emilios
Thanks!! your guide is amazing!
Ed
Thank you, well explained!
cocoa
Android need to hire you for explaining a lot of their stuff. The dev site is really…lacking
[…] you are confused about these graphics then look at this excellent post by @radley. With that in hand I fixed up the defective graphics and now all is “workie”.  While […]
What are the optimal sizes of a splashscreen image for an Android app? #Android…
Design big for 1920×1080 and 1080×1920 so you have that asset to base you other resolutions on and have them scale down flawlessly. I’m even seeing this done in html5 css3 apps now. In addition to being HD resolution and the size of the new android ub…
Nakes
Simple and clarifying explanation.
raptor41
That was very helpful and easy to understand, thanks!
Julio
Thanks a million. I worked many times with nine patch but now I understand perfectly how they work.
[…] For background reading take a look at: Simple Guide to 9 Patches […]
arun
I want to tile certain regions in a png.not the whole png. 9 patched areas only needs to be tiled. is it possible ?
radley
Tile or stretch? 9 patch is meant for stretching, not tiling. They’re simply opposing forms of math…
Mohamed Rafiq
Thanks a lot!!
The info is very helpful to gain more information on 9-patch for Android. It would be better if you could provide a simple example PSD… just a suggestion.
hey
thanx for sharing .
A good introduction to 9-patch images
[…] have to create a custom drawable nine patch file which hasn’t got a border. Here you find a tutorial And the […]
Good writeup!
Along with the multiple stretch regions, would be worthwhile to point out:
– trying to shrink the size of a 9patch (e.g. by specify height in xml that’s smaller than the image’s height) will typically result in nasty visual artefacts.
– some tools available for creating/editing.
Ifad Ardin
Your read my mind and answer my need. Thank you!
Zerho
The Stackoverflow link about multi line example is broken :(
radley
Oh well. I removed the reference to it since I couldn’t find another example. Thanks for letting me know!
Zuby
First of all thank you for nice tutorial. My lot of confusions get clear but still I am stuck in one thing. I am going to create a 9 path image for my button. But, I could not understand what should be its size for xhdpi, hdpi, ldpi and mdpi.
In tutorial you said image size should by 48×48 and after creating 1 pixel black line line its size become 50×50.
Questions:
1. Please tell me what should be original image size for xhdpi, hdpi, ldpi and mdpi?
2. Do I first create an image for xhdpi, hdpi, ldpi and mdpi and then separately create 9 path image?
radley
1. mdpi is the same as dp in size, so 48dp is 48 pixels on an mdpi device.
hdpi == 1.5x mdpi
xhdpi == 2x mdpi
xxhdpi == 3x mdpi
So if you have a 48×48 image, it will need to be 72×72 for hdpi and 96×96 for xhdpi. Adding a 9-scale border to each will make the files 50×50, 74×74, and 98×98.
2. Yeah, it’s best that way because Photoshop tends to add hard to see anti-aliasing which can break 9-scale markings. You’ll usually need to redraw by hand new guidelines, as well as run an eraser around the edge of the graphic, just to be sure it’s clean.
My compliments. In the ufficial docs it’s not clearly stated the different usage for the right/bottom guides and the top/left ones…
Vincent
Wanted to take a minute to tell you great job with your article! Exactly what I was looking for, clear explanation & examples!
Carmen
Thanks for this very helpful article!
For info, this article has been included here (though I didn’t see a citation): http://souravtechdiary.blogspot.fr/2012/02/all-about-9-patch-image-in-android.html
[…] Solution: don’t use that big images as backgrounds. Try nicely scalable images, and check out the 9-patch format: link […]
S.Dhanalakshmi
Very useful.Thank you.
[…] have tried to follow this explanation on the web but I am finding it difficult to understand. If anyone knows the correct resize for this […]
[…] image, but your image edges will be cut depending on screen size. Here is an article about it: Simple guide to 9-patch image. And also there is a good web-site to generate 9-patch images – Android Asset […]
[…] effort that I started my plow through the Android Design Guidelines this morning. I now know that 9 patch exists, and how to use it. (It’s a simple way to visually annotate a button to indicate which […]
[…] effort that I started my plow through the Android Design Guidelines this morning. I now know that 9 patch exists, and how to use it. (It’s a simple way to visually annotate a button to indicate which […]
[…] windows, buttons and other elements of variable dimension can be stretched out. For this, follow a 9-patch grid where the 4 corner patches remain unstretched, the left and right are stretched in height, the […]
Joe
This is the first place I have seen an example like the rounded asset you shown. Quite a nice trick
[…] Image source and more information: http://radleymarx.com/blog/simple-guide-to-9-patch/ […]
[…] 1. Android SDK — тут все просто, собираем под 4.2 или 4.3 и все счастливы. Под 2.2 в моем случае все работает нормально. 2. Подполнительные модули для Titanium — если не хватает основного функционала, существует вполне приличная база модулей расширяющих возможности. Все они доступны на titanium marketplace. Кроме того, можно написать свой собственный. 3. Android поддерживает «резиновые» картинки, называемые 9-patch. Подробнее о них можно почитать тут: developer.android.com/tools/help/draw9patch.html radleymarx.com/blog/simple-guide-to-9-patch/ […]
[…] like a 3×3 grid. then you only scale the middle on, the rest stay the same size but move. This link is for android but the same principles […]
[…] a la que se le ha asignado la imagen como background o source. Puedes encontrar más información aquí o aquí sobre la herramienta draw9patch. En la imagen que vamos a usar, hemos marcado con la […]
Will Capellaro
So the stretching that happens in the scaling areas, how is that handled? Is there smoothing or other upsampling methods applied? Looks like you trust a gradient in those areas, but it might be good to cover that, if it is known.
radley
For the most part it’s smooth. If you’re trying something very subtle, with little difference in a short area you may see banding. I’m used to seeing banding so I’ll often try gradients over and over until I get something smooth.
Tridib Ghosh
I am a fresher in mobile app designing field.
What is left scale & right scale?
Andrew
Thanks. I appreciate this explanation. Others (we will leave them nameless but they are well known) don’t do as good job explaining 9-patch as you have done here.
piero
Thank you, more easy to understand than official Google documentation
[…] is a lot of great material on the web to get the hang of it but I found this blog post by Radley Marx really helpful for me to understand the needed concepts. If you haven’t read […]
[…] to stretch elements any which way without distorting them. For in a more in-depth look at 9-Patches read this article. Now imagine the look of joy on your developers face when they realise what you have given […]
This is awesome Radley, thanks!
anoir
thanks, very good explanation.
Ritu
awesome article!!!
i hav written a code to click an image and set it on an imageview.
nw how do i stretch this image?? i.e. dynamically…
well done bro…i really appreciate those who are making life easy for developers..and u r one of them..thanks a a lot.. :)
Johnson Maung
a Few … But its a complete awesome Post….
Good post! I was not able am now able to to understand the 9-patch but done it bro! Hats off to you
Nobody
Thanks for the helpful input. But I am confused in your last scale & scale example. The text says “Left scale is not used, so height remains the same”, but the image beside shows a full left scale (from left top to left bottom). Shouldn’t it be empty instead?
radley
Android won’t recognize a 9-scale without something on the left side. That’s why I did a full bar, so it stretches naturally, which in this case is not at all.
Erika
Hi, im confuse the guides lines must be solid black or transparent ?… and when you save the image, you save in for example ths one is 48×48 but i save in 50×50?? please help!
Thank you !
[…] There’s a pretty decent explanation of what nine-patches are over here. […]
Alex
This was hugely helpful. I do have one question–if I’d like to create a stretchable icon with a non-stretchable graphic in the center, could I assign two individual stretch points across the top and two down the left to create a stretchable padding inside the icon?
radley
Yes, exactly like that.
Kouretinho
Best guide on the internet about NinePatch images. Thanks for sharing man. Android documentation is still (3 yrs later) so insufficient, it’s not even funny…
[…] gráfico que se pueda definir por medio de XML, o también se pueden crear imágenes de tipo 9Patch, a las cuales se les puede modificar sus dimensiones sin perder la calidad de la […]
Gordon Illan
Is there a way to fill the display with edge pixels without scaling the image in the center. For instance, if I have a 20×20 while circle in the center of a 100×100 red background, is it possible to stretch the red background only leaving the 20×20 circle intact? Thank you.
radley
Sure – add two stretch lines on either side of the circle, but not within the circle. The lines need to be the same length on each side so they stretch evenly on each side of the circle. Finally, if the outside area is a single color, you can just do a 1-pixel stretch line which will essentially stretch the color of the corresponding pixel.
the_new_mr
Thanks man! I thought I had padding understood but couldn’t find anywhere on the net that confirmed apart from your excellent post. Thanks again!
Mike
I’d like to echo everyone else’s sentiments: great guide!
I think one part of the guide is slightly misleading. In that bottom example with the three circular images inside the button of a fixed height, it says “Left guide is not used so height remains the same”
To me, that implies that if you put the 9patch in a layout taller than the button’s native height, and tell it to match_parent, it won’t grow at all (the “height remains the same”) and it will stay at its native height as though you had set it to wrap_content.
“Nobody” asked about this on on June 4 and you replied:
Android won’t recognize a 9-scale without something on the left side. That’s why I did a full bar, so it stretches naturally, which in this case is not at all.
So I tried this out, and it does indeed stretch vertically (“naturally” just like images normally stretch) . How is that “not at all”? I assume you mean it won’t stretch if you tell it that the height should wrap_content. Is that the only way to make a button not stretch vertically? There’s nothing you can do inside of the 9patch so it’ll ensure it won’t stretch even if it’s in a layout that tries to stretch it?
Thanks!
radley
Ah, good catch. Normally your ImageView container should limit the stretching. Otherwise, make your image’s canvas two pixels taller (but centered) and add two single-pixel scale marks on the left, each aligned with the new empty space. Make sure the new row is truly empty – you don’t want to stretch anti-aliased portions of your image.
Harish Pathak
I am trying to use 9-patch images in ios but maybe it’s not recognising these as 9 patch even i’ve named these images like abc.9.png
If i am using these images ‘a black border’ is coming. that is 1 px guide line as u said in ur tutorial. how to remove it.
or am I missing something, Please help!!!
K17
9patch is a Google designed, Android-specific file format. It does not run natively on iOS (though there may be libraries out there to support them).
radley
I’ve never done 9-scale for iOS, so can’t offer advice. Maybe someone else will chime in.
[…] a look at Radley Marx’s guide and Google’s guide on 9-patch […]
[…] a la que se le ha asignado la imagen como background o source. Puedes encontrar más información aquí y aquí sobre la herramienta draw9patch. En la imagen que vamos a usar, hemos marcado con la […]
[…] As far as I know, this type of image can help the developers to reduce apk size from assets side. Using this image, we can reduce the asset size but still get good quality of buttons. Before we start to make new .9.png image, better to know the structure of this image. Below is basic guide map I got from A Simple guide to 9-patch for Android UI. […]
[…] berarti desainer selain harus menyediakan asset dengan berbagai ukuran dpi juga harus menyediakan banyak Nine Patch apabila […]
Stephane
These round images are beautiful. Any way to have some ready made ?
The best guide on 9 patch I’ve seen. Helpful for a noob like me.
Kibi
Thanks so much – by far the simplest guide I have seen – helped me understand what wa wrong with my 9.png (black lines were thicker than one px)
[…] manually cutting and setting guidelines, but if you’re interested in learning more on how, this guide gives you all the information you’ll ever […]
[…] me and did it well. If you’re completely new to the concept head straight for the 9-patch bible – Radley’s simple guide to 9-patch. Others: follow […]
This is a great quick guide on what a nine patch is and how to create one.
Thuan Nguyen
This article really quick guide and helpful. Thank you so much.
[…] 參考及圖片來源: [Android アプリの UI デザイン] 9-patch の作りかたのまとめと Tips Android Studio Draw 9-patch A simple guide to 9-patch for Android UI […]
[…] Here you can find more detailed explanation about NinePatch. […]
[…] that will not cause it to look all nasty and stretched. There are a couple of great articles on what a 9-patch image is and how to use the draw9patch utility within the SDK to create one so I’ll not regurgitate […]
demba
black lines still be displaying in my app. how can i remove it?
thank
Radley
They have to be perfectly black lines. They can’t have a single pixel that’s less than black. The same thing with the transparent area: make sure there are no hidden “almost-invisible” pixels in there. It’s the result of Photoshop antialiasing when parts of your image are resized.
[…] is most appropriate for your application's UI. For tips and more information, take a look at this blog post by Radley Marx and in Google's Draw 9-patch documentation for […]

Leave a replyReply to

footer-logo

Twitch   •   Mastodon
Twitter   •   LinkedIn   •   Mixcloud

thank you for visiting  ❤︎
View