在可绘制的或其他方面拉伸一个像素宽的梯度图像

时间:2013-12-13 17:25:37

标签: android android-imageview drawable

我有一个PNG文件是一个像素宽,283像素高的渐变图像,我需要在ImageView的背景上拉伸,只能水平拉伸。我试图将资产设置为ImageView的背景,如下所示:

<ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/gradient_tile"
        android:layout_gravity="bottom|center"
        android:scaleType="matrix"/>

但只是在父视图的中间创建一个像素的行。

有没有办法做到这一点,还是我需要请求更宽的图像,并使用9补丁?

提前致谢。

更新: 我最终必须在XML中设置最小高度属性,如下所示:

<ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="119dp"
        android:background="@drawable/gradient_tile_drawable"
        android:id="@+id/tiledGradientBackground"
        android:layout_gravity="bottom|center"
        android:scaleType="matrix"/>

...然后将minimumWidth设置为代码中父视图的宽度。不知道为什么这会解决它,但它确实......

int width = holder.container.getResolvedWidth();
holder.tiledGradientBackground.setMinimumWidth(width);

2 个答案:

答案 0 :(得分:2)

试试这个(平铺而不是拉伸):

在您的drawable文件夹中输入一个名为 bg.xml 的文件:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/your_1px_wide_image"
    android:tileMode="repeat"
/>

并将其设置为您的布局背景

android:background="@drawable/bg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

我测试了它并且工作正常。

此图片

enter image description here

正在给出这个结果。

enter image description here

请注意,我添加了一些额外的填充 - 此屏幕宽度为320 * 480,因此渐变大约为总屏幕高度的1/3(包括标题和状态栏+额外填充)

答案 1 :(得分:2)

  1. scaletype影响ImageView的src图像,而不影响背景,如果图像视图仅用于背景,则将图像设置为src并使用fitXY scaletype。
  2. 你应该创建一个像Klaus66&amp; CommonsWare建议并将其设置为背景。
  3. 实际上,如果你有1px渐变,你可能只需创建一个GradientDrawable xml,在不同的设备上看起来会更好。 http://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html
  4. 您不应该使用额外的ImageView,只需将其设置为顶部布局的背景,甚至是主题的背景,请参阅我的答案:Android SplashScreen