Android:如何设置ImageButton的src图像的高度/宽度?

时间:2011-11-17 08:56:18

标签: android imagebutton

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

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

5 个答案:

答案 0 :(得分:20)

您可以使用scaleType的{​​{1}}属性。 根据需要将其设置为ImageButtonfitXY或其他任何内容。

像这样

fitCenter

答案 1 :(得分:6)

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

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

答案 2 :(得分:3)

<强> 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
            )
    );

答案 3 :(得分:3)

我有同样的问题......改变了'src&#39;的大小。图像按钮的图像(不是按钮的大小只是图像)。

我做了什么 -

  

我感动了那些&#39; .png&#39;来自&#39; drawable&#39;的档案文件夹到&#39; drawable-hdpi&#39;文件夹中。

很奇怪......但它确实有效。

感谢,

答案 4 :(得分:0)

  

设置填充并将比例类型设置为 centerInside

填充将帮助您自定义源图像以提供所需的高度和宽度。

 <ImageButton
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/location"
            android:padding="10dp"
            android:scaleType="centerInside"
            android:background="@drawable/blue_circle_border"/>
相关问题