如何实现不拉伸的 android:background? [英] How to implement an android:background that doesn't stretch?

查看:37
本文介绍了如何实现不拉伸的 android:background?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个很棒的线程描述了如何吃蛋糕,也吃蛋糕",即使用图像作为 Button 而不是 ImageButton(不允许 SetText()、调整大小等).

I found this great thread describing how to "eat the cake and have it too", i.e. use image for a Button instead of ImageButton (which doesn't allow SetText(), resizing, etc.).

这是通过使用 View 属性实现的:

This is achieved by using the View attribute:

android:background="@drawable/bgimage"

唯一的问题是它会拉伸图像以适应按钮大小.

The only problem with this is that it stretches the image to fit the button size.

没有硬编码固定按钮大小(以像素为单位!),有没有办法告诉 Android 完全拉伸背景图像并裁剪或填充它?

Short of hard-coding a fixed button size (in pixels!), is there a way to tell Android not to stretch the background image at all and either crop or pad it?

推荐答案

你应该使用 ImageView 如果你不想它拉伸.背景图像将始终拉伸以适应视图.您需要将其设置为 Drawable 以强制对象的图像方面.

You should use ImageView if you don't want it to stretch. Background images will always stretch to fit the view. You need to set it as a Drawable to force the image aspect to the object.

否则,如果您坚持按钮的想法,那么您将需要强制缩放按钮以防止图像拉伸.

Otherwise, if you are sticking with the Button idea, then you will need to force the scaling in the button to prevent the image from stretching.

代码:

onCreate(Bundle bundle) {
  // Set content layout, etc up here

  // Now adjust button sizes
  Button b = (Button) findViewById(R.id.somebutton);
  int someDimension = 50; //50pixels
  b.setWidth(someDimension);
  b.setHeight(someDimension);
}

这篇关于如何实现不拉伸的 android:background?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆