2011-11-17 165 views
9

Android:如何设置ImageButton图像的高度/宽度(背景的src图像intead)?Android:如何设置ImageButton的src图像的高度/宽度?

我想设置顶层图像(不是背景)图像的高度/宽度,图像的大小应当代替定制的fullfill按键自动

+0

可能重复:http://stackoverflow.com/questions/6899088/adjusting-the-size-of-an-imagebutton-in-android – 2011-11-17 09:00:16

+2

我想设置的高度/宽度顶级图像(不是背景)图像,图像的大小应该自定义,而不是自动填充按钮。 –

回答

2

XML

<ImageButton 
android:id="@+id/picture_id" 
android:layout_width="10dp" //here width with unit. 5 dp exemple 
android:layout_height="3dp" //here height with unit. 3 dp exemple 
android:src="@drawable/picture_name" 
/> 

编辑:(java代码)

// load the origial BitMap (500 x 500 px) 
    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), 
      R.drawable.android); 

    int width = bitmapOrg.width(); 
    int height = bitmapOrg.height(); 
    int newWidth = 200; 
    int newHeight = 200; 

    // calculate the scale - in this case = 0.4f 
    float scaleWidth = ((float) newWidth)/width; 
    float scaleHeight = ((float) newHeight)/height; 

    // create a matrix for the manipulation 
    Matrix matrix = new Matrix(); 
    // resize the bit map 
    matrix.postScale(scaleWidth, scaleHeight); 
    // rotate the Bitmap 
    matrix.postRotate(45); 

    // recreate the new Bitmap 
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, 
         width, height, matrix, true); 

    // make a Drawable from Bitmap to allow to set the BitMap 
    // to the ImageView, ImageButton or what ever 
    BitmapDrawable bmd = new BitmapDrawable(resizedBitmap); 

    ImageView imageView = new ImageView(this); 

    // set the Drawable on the ImageView 
    imageView.setImageDrawable(bmd); 

    // center the Image 
    imageView.setScaleType(ScaleType.CENTER); 

    // add ImageView to the Layout 
    linLayout.addView(imageView, 
      new LinearLayout.LayoutParams(
        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT 
      ) 
    ); 
+0

它只是调整整个按钮的宽度和高度,我想调整src图像。 –

+0

你可以用java代码来完成。 – damson

+0

谢谢,这对我来说有点复杂。我转而使用另一个图标走动。 –

6

您可以使用Bitmap.cr eateScaledBitmap将图像缩放到所需的大小。

Bitmap image = ... //load image from your source 
image = Bitmap.createScaledBitmap(image, desiredHeight, desiredWidth, true); 
+0

根据[docs](https://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap)将尺寸倒置,你需要像这样:'image = Bitmap.createScaledBitmap( image,desiredWidth,desiredHeight,true);' –

19

你可以使用的ImageButtonscaleType属性。 根据您的需要将其设置为fitXYfitCenter或其他任何东西。

这样

<ImageButton 
    android:id="@+id/imageButton" 
    android:layout_width="100dp" 
    android:layout_height="100dp" 
    android:scaleType="fitCenter" 
    android:src="@drawable/some_image"> 
</ImageButton> 
+2

这应该是公认的答案。 – MeetTitan

+1

这不回答问题。问题是要求设置'android:src'而不是整个'ImageButton'的大小。例如。具有一个100dp x 100dp的ImageButton和35dp x 35dp的src图像 – Weizhi

3

我有同样的问题...更改图像按钮的“SRC”图像的大小(按钮的不是大小只是图像只)。

我did--

我感动从‘绘制’文件夹中的“png格式”文件‘绘制,华电国际’文件夹。

奇怪......但它的工作。

感谢,

相关问题