如何通过保持纵横比来填充ImageView中的图像?

时间:2012-07-30 16:03:47

标签: android user-interface

我在同一主题上看到很多问题,并尝试使用

android:adjustViewBounds="true"
android:scaleType="fitCenter"

我的图像仍然按原样显示。如果我改变了

  

机器人:scaleType = “fitCenter”

fitXY正常工作。但是根据文档,这个不保持宽高比。那么如何更改代码才能按预期工作?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/card"
        android:layout_marginTop="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/card" >

        <ImageView
            android:id="@+id/idImage"
            android:layout_width="fill_parent"
            android:layout_height="110dp"
            android:layout_margin="10dp"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/783454" />

    </LinearLayout>

</LinearLayout>

![在此处输入图片说明] [1] ![在此输入图像说明] [2] 我错过了这个概念?

1 个答案:

答案 0 :(得分:0)

请查看此代码,这就是我正在缩放位图以正确适应屏幕的方式。也许它会有所帮助,并为您提供有关您的任务的想法。

private void loadImage() {
    ImageView imageView = (ImageView)findViewById(R.id.imageView);

    Bitmap imageBitmap = ... load original image bitmap;  

    Bitmap scaledBitmap = imageBitmap; 

    // Scaling

    int imgSrcHeight = imageBitmap.getHeight();
    int imgSrcWidth = imageBitmap.getWidth();

    int scaledHeight = 0;
    int scaledWidth = 0;

    int ctnrHeight = imageView.getMeasuredHeight();
    int ctnrWidth = imageView.getMeasuredWidth();

    int mHeight = imgSrcHeight - ctnrHeight;
    int mWidth = imgSrcWidth - ctnrWidth;

    if(mHeight > 0 && mWidth > 0)
    {
        if(mHeight > mWidth)
        {
            // scale to fit height
            if(mHeight > 0)
            {
                scaledHeight = ctnrHeight;

                // if height < 0 it means it's already inside of content
                int coefOverhight = (ctnrHeight * 100)/imgSrcHeight;
                scaledWidth = (int)(imgSrcWidth * ((coefOverhight)/100.0)); 
            }
        }
        else
        {
            // scale to fit width
            if(mWidth > 0)
            {
                scaledWidth = ctnrWidth;
                int coefOverwidth = (ctnrWidth * 100)/imgSrcWidth;
                scaledHeight = (int)(imgSrcHeight * ((coefOverwidth)/100.0));
            }
        }
    }
    else
    {
        scaledHeight = imgSrcHeight;
        scaledWidth = imgSrcWidth;
    }

    scaledBitmap = Bitmap.createScaledBitmap(imageBitmap, scaledWidth, scaledHeight, true);


    imageView.setImageBitmap(scaledBitmap);

}