歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 中9-patch與padding

Android 中9-patch與padding

日期:2017/3/1 10:14:47   编辑:Linux編程

前幾天遇到這樣一個問題

我們做的應用客戶看了說UI有問題,本來是一個正方形的區域,呈現的結果卻是長方形,有些偏差

之後我就開始修改,覺得UI問題肯定是哪裡沒有設計好,95%是因為xml裡面配置錯了,這是我第一直覺.

找了一上午,發現xml裡面沒有問題,定義的確實是正方形區域,也沒有任何padding設置.於是下午就在代碼中找,看看是不是代碼中設置padding

我覺得一般人不會在代碼中干這種事情吧,果然,沒有找到.汗了!


於是開始debug,代碼中也沒有什麼特別的設置,很崩潰.後來發現setBackgroundResource這個api有些詭異

其中調用了void Android.view.View.setBackgroundDrawable(Drawable d),setBackgroundDrawable方法中有這麼一句

  1. setPaddingFromDrawable(d, padding);

這是啥......怎麼看上去這麼詭異,setPaddingFromDrawable有

  1. draw.getPadding(padding)

debug發現,走過這裡,padding就被改變了.然後沒有繼續深入調查,猜測和android:background的設置有關,去掉這個設置,padding不見了

後來美工證實了我的猜想,padding是寫在了9patch圖片裡面.


所以當你在xml和代碼中找不到padding的設置,而結果卻有padding效果時,那基本應該就是9-patch干的好事了


下面就簡單學習下9-patch

拿原生Email為例吧,隨便找了個.9圖片:attachment_bg_holo.9.png(packages/apps/Email/res/drawable-hdpi)

sdk為我們提供了查看9-patch圖片的工具,在tools文件夾下

android-sdk/tools$ ./draw9patch

打開上述圖片:


下面幾個滑動條看上去很別扭是因為我把工具頁面縮小然後他們被擠到一起了

當你滑動patch scale時,右邊的預覽也會隨著改變大小

下面先說說padding在哪

中間的圖片四周帶有黑線(點)的就是我們打開的.9圖片

黑色部分又分為兩部分,其中下和右兩條黑線(點)控制padding

勾選show lock後會看到圖片區域(就是現在我的截圖去掉四周一圈)

那麼上下左右padding分別是多少呢?

很簡單,一個小格子是一個像素

上下左右padding分別是2,3,2,2(要去掉最外圈的格子,因為他們不是圖片的一部分)

那麼我說的對不對,如何檢驗,sdk提供了另一個工具在tools文件夾下hierarchyviewer

android-sdk/tools$ ./draw9patch


看到右邊的數值了吧.

下面是官方的說明

guide/topics/graphics/2d-graphics.html#nine-patch You can also define an optional drawable section of the image (effectively, the padding lines) by drawing a line on the right and bottom lines. If a View object sets the NinePatch as its background and then specifies the View's text, it will stretch itself so that all the text fits inside only the area designated by the right and bottom lines (if included). If the padding lines are not included, Android uses the left and top lines to define this drawable area.


下面看看9-patch上邊和左邊的黑線是做什麼的

下面是http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch的圖片


我想大家也看明白了,另外的兩條線是控制拉伸區域的,可以是一條也可以是多條

下面是官方說明

guide/topics/graphics/2d-graphics.html#nine-patch 寫道 The border is used to define the stretchable and static areas of the image. You indicate a stretchable section by drawing one (or more) 1-pixel-wide black line(s) in the left and top part of the border (the other border pixels should be fully transparent or white). You can have as many stretchable sections as you want: their relative size stays the same, so the largest sections always remain the largest

至此,關於9-patch的講解結束,如有更多需求和疑問請移步下列地址

http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

http://developer.android.com/reference/android/graphics/NinePatch.html

http://developer.android.com/guide/developing/tools/draw9patch.html

Copyright © Linux教程網 All Rights Reserved