Patch images in android

Android Nine Patch Image Example

When you want to use an image as a view object background, for example, you need to use a bubble chat image as a chat app text message background, you can find that the text message may stretch the background image unwanted as below.

Android studio provides tools for you to resolve such problems. You can use that tool to change the background image to a nine-patch format image. Then you can get the correct stretched image like below.

This article will show you how to use the android studio nine-patch tool to create and use the nine-patch image.

1. What Is Nine Patch Image.

  1. Nine patch image is an android special image format that can make the background image scaled correctly. So the image can be used in different size android devices such as mobile phones, android pads, etc.
  2. The nine-patch image should be a png image. And only support that format image. You can not change an image suffix from jpg to png to make it possible.
  3. Nine patch image suffix is .9.png. You can not change a png file suffix manually to make that image nine-patch format, you need to use the android studio nine-patch image tool to convert it. Otherwise, you may encounter an unexpected error.

2. How To Create A Nine Patch Image.

  1. First, add a .png image to the android project drawable folder. You can read How To Add Images In Android Studio Drawable Folder to learn more.
  2. After that, right-click the original .png image ( bubble_chat_icon.png ). Then click the Create 9-Patch file… menu item in the popup menu list.
  3. After that, you will find the same name .png image with .9.png suffix ( bubble_chat_icon.9.png ) is created in the drawable folder.
  4. Double click the newly created image, there are two panels opened. The left panel is the adjustable 9 patch image, the right panel is the resulting image after the left panel image is adjusted.
  5. The first image in the right panel shows the vertical direction adjusted result. The second image in the right panel shows the horizontal direction adjusted result. The third image shows both directions adjusted results.
  6. To adjust the image stretchable area, you can first click a black point in the left panel image border, then you can drag the black point to specify the border stretchable area. Then the right panel will show the adjusted result immediately. You can see this step demo video on youtube URL https://youtu.be/0eEt6XHmKS4.

3. Nine Patch Image Example.

3.1 Main Layout XML File.

  1. activity_nine_patch_image.xml
Читайте также:  Android spinner set selected item

3.2 Activity Java File.

  1. NinePatchImageActivity.java

3.3 Nine Patch Image Example 1.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/E_KzW9KKw5Q

  1. This example stretches two border straight lines for the 9 patch image.
  2. Example 1 result.

3.4 Nine Patch Image Example 2.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/kfEoFrRl1vU

  1. This example stretches two corners for the 9 patch image.
  2. Example 2 result.

3.5 Nine Patch Image Example 3.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/jISn_kq5-ms

  1. This example stretches one corner for the 9 patch image.
  2. Example 3 result.

Источник

Создание и использование 9-патч-изображений в Android

Недавно я услышал о 9-патч-изображениях. Я знаю его 9 плиток и растяжимых. Я хотел бы узнать больше об этом.

Как создать 9-патч-образ?

Есть ли какой-нибудь инструмент? Могу ли я создать его из AndroidSDK или кода?

Основные преимущества 9-патча поверх обычного png?

(он растягивается динамически/автоматически в соответствии с экраном?)

ОТВЕТЫ

Ответ 1

Сегодня я обнаружил девять патч-изображений. Документация, связанная с другими ответами, в порядке, я полагаю, но на самом деле им не хватает примеров. В этом маленьком учебнике есть несколько замечательных примеров, которые отвечают на вторую часть вашего вопроса, объясняя, как работает масштабирование — не только для кнопок, но и для фреймов. В девятом патче можно указать непересекающиеся области для масштабирования.

Чтобы отфильтровать ответы на первую часть вашего вопроса, SDK поставляется с «draw9patch» (в папке с инструментами), который является простым редактором. Вот еще один загружаемый файл, который хорош, и имеет простой, но умный образ по умолчанию.

Ответ 2

В большинстве примеров говорится о создании 9-патч-образа, но детали реализации обычно остаются на высоком уровне.

Ник пост выше — с хорошим 9-патч-учебником, который обеспечивает файл загрузки рабочего проекта, сохраненный день.

Вот основные детали реализации, которые работали для меня (после того, как у вас есть 9-патч-образ, готовый к работе):

Ссылка на drawable с именем, но не включающим .9.png(автозаполнение в eclipse позаботится об этом)

Удостоверьтесь, что у вас есть только 1 изображение в папке с основным/доступным (не версия для каждой папки с тэгами)

Изображение должно быть указано с использованием: background, not: src (это заставило меня застрять некоторое время)

Убедитесь, что содержащееся в нем изображение и макет:

Ответ 3

Как создать 9-патч-образ? Есть ли какой-нибудь инструмент? Могу ли я создать его из AndroidSDK или кода?

При поиске основной поисковой системы для android 9-patch tool самый первый хит для страницы документации разработчика Android в инструменте draw9patch /a > .

Основные преимущества 9-патча поверх обычного png? (он растягивается динамически/автоматически в соответствии с экраном?)

Документация разработчика Android содержит другие страницы, которые описывают файлы с девятью патчами PNG. Эта документация включает в себя такие проходы, как:

Графика NinePatchDrawable — это растягиваемое растровое изображение, которое Android автоматически изменит размер, чтобы разместить содержимое представления, в которое вы поместили его в качестве фона. Пример использования NinePatch — это фон, используемый стандартными кнопками Android — кнопки должны растягиваться для размещения строк различной длины.

Ответ 4

С 9-патч-изображением вы можете выбрать, какая часть вашего изображения может быть растянута. Это должно быть png-изображение, а имя должно заканчиваться на .9.png(something.9.png)

Читайте также:  Descargar juegos android para android

Простой инструмент для всех плотностей:

Ответ 5

1. Каковы изображения NinePatch?

Изображения NinePatch представляют собой изображения PNG, которые отмечают части изображения, которые могут быть растянуты. Они имеют расширение, подобное image_name.9.png .

2. Где они хранятся в проекте Android?

3.Как создать образ NinePatch для вашего анддроидного приложения?

Android SDK включает инструмент WYSIWIG draw9patch.jar в вашей папке Android SDK /tools .

Ответ 6

Основные преимущества 9-патча поверх обычного png

Фактически 9 патчей изображения растягиваются, повторяемые изображения уменьшаются до наименьшего размера. Изображение не будет растягиваться и распускать пропорции в разных размерах экрана. Еще одним преимуществом является память.

Одинаковая память небольшого размера может быть повторно использована для разных устройств размера экрана. Хорошо продуманные 9-патч-изображения менее подвержены ошибкам и имеют высокую повторяемость.

Ответ 7

Это хороший инструмент: Нажмите здесь.

9 Патч-изображения растягиваются, повторяемые изображения уменьшаются до наименьшего размера. Простейшим примером могло бы быть, если бы вы взяли закругленный div и нарезали его на 9 квадратов, как если бы вы использовали плату tic-tac-toe. Четыре угла не изменили бы размеры вообще, но были бы статическими, в то время как остальные 5 частей были бы растянуты или повторены, чтобы позволить всему изображению масштабироваться соответствующим образом.

С этим объяснением и появлением CSS3 вы можете подумать, что нет оснований использовать 9 патч-образов, но имя «9 patch» является неправильным. Изображения можно нарезать на еще более мелкие куски.

9 Патч-изображения содержат индекс, частью которого является то, что добавив границу 1px к изображению. Цвета на границе определяют, является ли кусок статичным (не масштабируется), он растягивается или повторяется.

Источник

Working with 9-patch (Nine Patch) images in Android

Nine patch ( 9-patch ) images are normal images with an additional 1 pixel border. This additional 1 pixel border is used to define

1. the scalable portion of the image

2. the portion of the image where the Android’s view object can render the content ( eg : caption of a button )

Demonstrating the use of 9-patch image

Please see the images( Figure1, Figure2 and Figure3 ) given below.

Figure 1 : Normal image

Figure 2 : Patched Image

Figure 3 : Buttons with Normal Image and Patched Image

  • Button1 uses the image shown in Figure1 as background image
  • Button2 uses the patched image shown in Figure2 as background image
  • In the case of Button1, the whole shape of the button is changed from its original background image. Also the edges of the button is blurred.
  • In the case of Button2, the shape of the button remains unchanged as well as the edges are still sharp in appearance. Due to these reasons, the use of nine patch ( 9-patch) images are highly entertained.

Now let us see, how the application shown in Figure3 is developed.

For its development, Eclipse 3.7.2 is used and is tested in Android Virtual Device of API 2.3.

The patched image is created using the tool draw9patch which is shipped with Android SDK and is available in its tools directory.

1. Create a new Android project namely “NinePatchDemo”

Figure 4 : New Android Project

2. Select Android build target

Figure 5: Select Androd Built Target

3. Enter application details

Figure 6 : Enter Application Details

Читайте также:  Toon blast для андроид

4.res/values/strings.xml

5. res/layout/main.xml

6. Get a background image

Create a new background image with a size of approximately 64 x 48 px and store it in the folder res/drawable-mdpi. The background image used in this application is available here.

7. Apply 9-patch to the above image

On the above image, apply 9-patch. How to apply 9-patch is described in step 9. The 9-patch image used in this application is available here.

8. Run the application

Figure 7 : Application in execution

9. Applying 9-Patch on the image

A. Open the tool draw9patch which is available in the tools directory of the Android SDK

Figure 8 : Open draw9patch

B. Open the normal image in draw9patch

Figure 9 : Open the normal image

C. Set the scalable portion of the image by filling left and top border pixels with black color

Figure 10 : Mark Scalable portion

D. Set the content portion of the image by filling right and bottom border pixels with black color

Figure 11 : Mark the content Portion

E. Save the file with an extension of .9.png

F. The patch file is ready now, and it can be used in the application

Источник

9patch images in Android

Using and creating 9-patch images is actually quit simple. Just keep in mind which area is stretched and which area will be repeated. Because I couldn’t find any resources ofor this topic I’ve created some 9 patch images myself. Use it for your own projects. No, I don’t use any licence for this, just use it and make tons of money with it!

I’ve created two sets of images:

  1. Matte images, best for android and stretchable buttons.
  2. Glossy images, use this when there is just a single line of text.

Matte images

Here some matte images, stretched to full width.

These are the original images used to create the screenshot. Right click, save as etc…
Make sureto save the images with a filename.9.png name. Otherwise it won’t work.

GlossyImages

How to use these images?

Well, that’s quit simple,just drop these images in a drawable folder of your project and set it as a background of a button. I’ve put all these images in the drawable-hdpi folder. Created a button style in strings.xml like:

Thenn, just create a layout with some buttons:

Ofcourse it is possible to setup a more rubust environment where a button will have multiple states. Therefore we need a selector file which is just a simple xml file stored in the drawablefolder. Just call it btn_blue_states.xml or something like that. This file will contain state definitions of the buttons:

Now, use the file name as a background for a button and you can use multiple states for a button while using 9-patch images!

Folkert

I’m a webdeveloper, looking for the best experience, working between development and design. Just a creative programmer. When I’m getting tired of programming C#, i’d love to create 3D images in 3D Studio Max, play the guitar, create an app for Android or crush some plastics on a climbing wall or try to stay alive when i´m descending some nice white powdered snowy mountains on my snowboard.

Источник

Оцените статью