9 Patch图像中心为1:1。

11
我想在Android上创建一个启动画面,并在中间放置一个小标志,但是该标志在更大的设备上会被拉伸。我认为我可以使用9图像,但是似乎9图像的工作方式与我想要达到的相反。
这是应该在中间的标志。
这是当我将图像设置为9 patch时得到的结果。 中心区域被拉伸了,角落保持原样。 我需要相反的效果。 我需要一个9 patch图像,它可以定义一个始终以正确的1:1比例显示的中心区域,以及在图像小于屏幕时可以拉伸左侧、右侧、顶部和底部的边框区域。
我该如何做到这一点?有没有用9图像都可以。
6个回答

10

以下是如何实现的示例。这是一个9patch图像,所以请将其保存为yourname.9.png,并不要忘记在ImageView上设置android:scaleType="fitXY"

enter image description here


3
这个很好用。你能解释一下你是如何创建这个9Patch图案的吗?(在哪里可以找到这些patches?)解释得越详细越好。 - RayLoveless

7
你可能需要标记四个拉伸位置。可以将下面的X标记替换为一个点。 如果还没有使用9path工具,请在SDK文件夹中使用它,以预览Android SDK将生成的内容。
    X       X
  ************
X ************
  ************
  ****LOGO****
  ************
X ************
  ************

使用这种方法并不总是能将标志放在屏幕中央。 - RayLoveless
采用这种方法,标志并不总是位于屏幕中心。 - Michael

2

如果只是在背景颜色中心放置一个标志,您可以尝试以下方法:

无需使用9-patch。只需使用普通图像(此处称为“splash_logo”),并通过创建新的可绘制XML文件(位于res / drawable内)来包装它:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <color android:color="@color/default_background" />
    </item>
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/splash_logo" >
        </bitmap>
    </item>

</layer-list>

在想要使用的imageView上使用这个drawable。

如果是全屏,你可以进一步使用第一个activity的主题,从而无需创建任何视图:

在styles.xml(或theme.xml)中:

<style name="SplashTheme" parent="@android:style/Theme.NoTitleBar">
    <!-- Background color must match splash image borders ! -->
    <item name="android:windowBackground">@drawable/activity_splash</item>
    <item name="android:background">@null</item>
</style>

并在清单文件中:

    <activity
        android:name="..."
        android:theme="@style/SplashTheme" >

2
您有两种解决方案:
  1. 将闪屏设置为具有您正在使用的蓝色背景的RelativeLayout。在此RelativeLayout中添加一个居中的图像。
  2. 正确使用9-patch。您需要在每个角上使用4个补丁:

enter image description here


使用9-patch的“正确方式”是在每个角上使用4个图案,这会拉伸中心的标志...这正是他想要避免的。 - RayLoveless
@RayL 这个问题很老了,但我相信在角落处修补图像不会拉伸标志。它将拉伸顶部和底部行以及左侧和右侧列。 - Sherif elKhatib
中心补丁在垂直和水平方向上都可以拉伸。试试看吧。这里有一个由谷歌维护的九宫格工具。http://romannurik.github.io/AndroidAssetStudio/nine-patches.html - RayLoveless

1
9-patch不用于这种渲染方式。(http://developer.android.com/tools/help/draw9patch.html) 但是您可以按照下面的代码,使用div并使用gravity进行居中。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:gravity="center" >

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world"
    android:src="@drawable/your_logo" />


1
你需要指定9-patch图像中哪些部分会被拉伸,这些部分在顶部和左侧边框的像素中填充即可。所以只需填充靠近边缘的像素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接