android中使用Nine-Patch图片

android中可以把图片进行处理,如果图片被拉伸的话,允许让图片部分区域不拉伸,部分区域拉伸。这个功能非常好,比如聊天的气泡,如果整个气泡被拉伸的话,会非常的丑。

老版的sdk中提供的有draw9patch.bat文件,允许对图片进行该项处理,不过新版的已经没有这个文件了,而是被集成到了Android Studio工具中。

首先先把图片放到项目中,注意只支持png格式的图片,右键这个图片,Create 9-Patch file

打开一个生成好的9-Patch图片,就可以进行处理了,鼠标右键按住不松,从左到右,从上到下,设置允许拉伸的区域。下面是我对聊天气泡的处理:

注意看左边的源图,上边和右边都有一条黑线,指的是我设置的允许被拉伸的区域,右边的预览图可以看到,经过处理后,不管是上下拉伸,还是左右拉伸,聊天气泡都不会变形了。

我用这个图片做了一个简单的Activity,代码如下,activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:background="@drawable/chat"
        android:gravity="center_vertical"
        android:text="内容1" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:background="@drawable/chat"
        android:gravity="center_vertical"
        android:text="内容2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

</android.support.constraint.ConstraintLayout>

效果如下:

 附聊天气泡原图:chat.zip

猜你喜欢

转载自www.cnblogs.com/modou/p/10248173.html