Android:如何防止ImageView或ImageButton中的图像缩放?

9
如何防止ImageView或ImageButton在使用“fill_parent”或“weight”进行拉伸时自动缩放位图?例如,在屏幕顶部创建一个4个按钮的工具栏,其中按钮间距相等,但是即使使用scaleType =“center”,图像仍然会被拉伸,这应该根据文档防止缩放,但实际上并没有。有任何见解都将不胜感激!谢谢。
3个回答

10

我发现在使用android:background时,图片会被自动缩放到View的大小。

我尝试使用android:src将图片放在视图中。 图片没有缩放,但我无法使其相对于View的大小居中。

因此,我尝试将整个按钮设为自己的相对布局,并使用以下内容:

<RelativeLayout android:id="@+id/RelativeLayout01" 
                android:layout_height="fill_parent" 
                android:layout_width="fill_parent">
                <ImageButton android:id="@+id/ImageButton01"    
                             android:layout_height="fill_parent"
                             android:layout_width="fill_parent"></ImageButton>
                <ImageView android:id="@+id/ImageView01"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content" 
                           android:background="@drawable/cardback1" 
                           android:layout_centerInParent="true"></ImageView>
</RelativeLayout>

ImageButton位于后台,始终与布局相同大小。 ImageView则始终居中于RelativeLayout中且不会缩放。这样,RelativeLayout本身可以增长和移动,而按钮上方的图像始终保持相同的大小,但按钮将增大。如果布局变小于图像本身,则图像将缩小。

我认为这就是您要寻找的内容。可能有更好的方法来实现这一点,但这是我现在能想到的全部。


17
不需要这样做,只需不使用android:background。改用android:src(ImageView),或android:drawableLeft/Right/Bottom/Top(Button或ImageView),或android:button(ImageButton)。 - Romain Guy
@Romain:我们不能使用9-patch可绘制对象作为按钮背景吗?我们可以将按钮的图标部分标记为不可拉伸,将其周围的所有额外空间(图标周围的填充)标记为可拉伸。这样,当调整背景大小时,只会拉伸额外的部分。 - Samuh
1
谢谢Matt和Romain,android:src正是我要找的东西。解决了我的问题 :-) - user277827
2
@Samuh:是的,你可以这样做,但为什么要麻烦呢?有一个属性可以实现这个功能。 - Romain Guy
3
此外,在使用 android:src 设置图像时,使用 android:background="@null" 将背景设置为透明会有所帮助。 - Error 454
1
如果您是在代码中动态地执行此操作(而不是在XML中),请使用imageView.setImageResource(R.drawable._____)。 - cyber-monk

3

只需修改您的可绘制图形,应用更大的透明背景。假设我的hdpi中可绘制图形是41×48像素的icon.png。我创建了一个60×60像素的新图像,具有透明背景,复制并粘贴以前的icon.png,并以相同的名称保存。这样您就不需要触摸您的布局。

然后,如果应用非透明android:background,您可以检查按钮区域是否更大:

<ImageButton android:id="@+id/widget_open"
android:src="@drawable/icon_widget_arrow_up"
android:background="#ff777777"
android:layout_height="wrap_content"
android:layout_width="wrap_content"></ImageButton>

将之前和新的可绘制对象应用到 android:src,您应该清晰地看到 ImageButton 区域。

顺便说一下,我正在兼容性模式下运行该应用程序。


不建议使用,可能会导致不必要的透支。 - Asthme

2

如果图像被缩放,请确保您的应用程序未在兼容性模式下运行(例如,如果您针对Android 1.5/1.6目标平台而不支持多个密度,并且您在Android 2.0上运行应用程序)。


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