将ImageView缩放到设备宽度

时间:2011-02-02 17:30:16

标签: android layout imageview

在我的Android应用中,我有一个活动,显示的图片大小为244 x 330。 我想以完整的设备宽度显示这些图像。

我的布局文件如下所示:

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

    <LinearLayout 
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical">

            <ImageView android:id="@+id/news_image" 
                android:layout_height="fill_parent" 
                android:layout_width="fill_parent"
                android:layout_marginLeft="18dip"
                android:layout_marginRight="18dip"
                android:background="#aaaaaa" />


    </LinearLayout>

</ScrollView>

我尝试设置ImageView的ScaleType,但没有ScalingType可以按比例缩放ImageView。 如何在横向模式和纵向模式下按比例缩放图像以适合整个屏幕?

基本上我想要的是ScaleType.CENTER_CORP,但它也设置了图像的比例高度,所以我可以看到它的全部而不仅仅是图像的一部分。

编辑原因我知道我对你的“怪异”任务感到困惑。

我想用图片向你展示。 这就是我目前使用布局获得的内容。我希望通过根据需要缩放图像来填充整个灰色区域。我怎么能做到这一点?

当我将ScaleType设置为CENTER_CROP时,我得到了这个

但这不是我想要的,因为你没有看到整个图像只是中心的一部分。

这就是我想要的:

我希望这可以帮助你理解我想要完成的事情。 谁知道怎么做?

编辑2:

我试图显示高度比屏幕尺寸更大的图像可能看起来很奇怪而且有点混乱但是因为我在我的示例布局中使用ScrollView这应该没问题如果用户想要查看未显示的区域,则可以滚动。

希望这有助于理解我正在尝试做什么。

9 个答案:

答案 0 :(得分:29)

ScaleType ImageView fill_parent wrap_content<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/news_wrapper"> <ImageView android:id="@+id/news_image" android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_marginLeft="18dip" android:layout_marginRight="18dip" android:background="#aaaaaa" /> </LinearLayout> </ScrollView> 的每个public class ScalingImages extends Activity { private ImageView imageView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test_margin); this.imageView = (ImageView)findViewById(R.id.news_image); // The image is coming from resource folder but it could also // load from the internet or whatever Drawable drawable = getResources().getDrawable(R.drawable.img); Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); // Get scaling factor to fit the max possible width of the ImageView float scalingFactor = this.getBitmapScalingFactor(bitmap); // Create a new bitmap with the scaling factor Bitmap newBitmap = Util.ScaleBitmap(bitmap, scalingFactor); // Set the bitmap as the ImageView source this.imageView.setImageBitmap(newBitmap); } private float getBitmapScalingFactor(Bitmap bm) { // Get display width from device int displayWidth = getWindowManager().getDefaultDisplay().getWidth(); // Get margin to use it for calculating to max width of the ImageView LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)this.imageView.getLayoutParams(); int leftMargin = layoutParams.leftMargin; int rightMargin = layoutParams.rightMargin; // Calculate the max width of the imageView int imageViewWidth = displayWidth - (leftMargin + rightMargin); // Calculate scaling factor and return it return ( (float) imageViewWidth / (float) bm.getWidth() ); } } 都尝试过,但没有一个有效。我也尝试了我在谷歌上发现的所有内容,但对我来说没有任何作用,所以我自己想出了一些东西。

很明显,ImageView没有缩放我的图像,因为我想缩放,所以我必须自己缩放它。缩放位图后,我会将新的Bitmap设置为ImageView的图像源。这非常好用,在G1和摩托罗拉Milestone 2上看起来非常好。

以下是我的所有代码

布局:

public class Util {

    public static Bitmap ScaleBitmap(Bitmap bm, float scalingFactor) {
        int scaleHeight = (int) (bm.getHeight() * scalingFactor);
        int scaleWidth = (int) (bm.getWidth() * scalingFactor);

        return Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
    }

}

活动

{{1}}

Util class

{{1}}

如果有更好或更准确的方法来完成相同的缩放请让我知道因为我无法相信这么微不足道的事情很难实现。

我真的希望看到更好的方法来做到这一点。

感谢您的阅读。

答案 1 :(得分:19)

最简单的方法是添加android:adjustViewBounds =&#34; true&#34;到ImageView并将比例类型设置为&#34; fitCenter&#34;

答案 2 :(得分:3)

确切地说,对你正在寻找的东西感到有些困惑。如果你正在缩放以适应屏幕,你有三个选项,如果你保持比例,其中两个是可行的。您可以使用ScaleType fitCenter,它会使图像按比例适合边界,或者您可以使用centerCrop(您说过您尝试过),它将拉伸图像的最短边以适合容器(意味着一些会被裁掉)在较长的维度上)。如果没有裁剪或不成比例地伸展,你不能伸展以适应宽度和高度。

编辑:好的,我想我现在明白了。首先,我将LinearLayout设置为wrap_content作为高度。其次,在代码中,这是我能想到的一种方法。您可以通过首先获取屏幕尺寸,然后使用新尺寸执行createScaledBitmap,然后设置背景资源来实现此目的。

final ImageView newsImage = (ImageView)findViewById(R.id.news_image);

//get details on resolution from the display
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

//going to set what happens as the layout happens
newsImage.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {

        public void onGlobalLayout() {
            int oldHeight, oldWidth, newHeight, newWidth;

            //we want the new width to be as wide as the screen
            newWidth = metrics.widthPixels;

            oldHeight = newsImage.getDrawable().getIntrinsicHeight();
            oldWidth = newsImage.getDrawable().getIntrinsicWidth();

            //keeping the aspect ratio, the new height should be w1/h1 = w2/h2
            newHeight = Math.floor((oldHeight * newWidth) / oldWidth);
            LinearLayout.LayoutParams params = 
                (LinearLayout.LayoutParams)newsImage.getLayoutParams();
            params.height = newHeight;
            params.width = newWidth;
            newsImage.setLayoutParams(params);
            newsImage.setScaleType(ScaleType.CENTER);
            newsImage.invalidate();
            newsImage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    }
}

答案 3 :(得分:3)

我在各地搜索,无法找到解决方案。 这就是我所做的,这对我有用,并带有滚动视图。

XML文件:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true" >

    <ImageView
        android:id="@+id/manga_page_image"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter" />
</ScrollView>

答案 4 :(得分:2)

您是否尝试通过ImageView.setScaleType()以编程方式设置?

setAdjustViewBounds( false )也可能会有所帮助。

编辑:抱歉,我误读了这个问题。无论如何,setAdjustViewBounds() 仍然可能会有所帮助。从来没有用过它。

答案 5 :(得分:2)

  

我想完整地展示这些图片   设备宽度。

这很简单。您只有错误的边距设置。删除这些行,您的图像将以完整的设备宽度显示:

android:layout_marginLeft="18dip"
android:layout_marginRight="18dip" 

答案 6 :(得分:1)

我不再看到图像了,问题已经过时了,以防万一其他人发现这个并且遇到同样的问题。获取float screenWidth = getResources().getDisplayMetrics().widthPixels并以编程方式设置ImageView LayoutParamters以将图像缩放为screenWidth不是更好。只是一个想法!!

答案 7 :(得分:1)

设法实现我想要的目标,希望与您的目标相同:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pgviewer);

    ImageView PgContainer = (ImageView)findViewById(R.id.imageView1);

    String Page = String.valueOf(getIntent().getExtras().getInt("Page"));
    try {
        PgContainer.setImageBitmap(getBitmapFromAsset(Page));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    PgContainer.setScaleType(ScaleType.FIT_CENTER);
    PgContainer.scrollTo(0, 0);
    PgContainer.setScrollBarStyle(0);
}

然后缩放位图:

private Bitmap getBitmapFromAsset(String strName) throws IOException
{
    AssetManager assetManager = getAssets();
    InputStream istr = assetManager.open(strName+".png");
    Bitmap bitmap = BitmapFactory.decodeStream(istr);

    float screenWidth = getResources().getDisplayMetrics().widthPixels;
    int ih=bitmap.getHeight();
    int iw=bitmap.getWidth();
    float scalefactor = screenWidth/iw;
    //w = 480, h=~
    //int newh = bitmap.getHeight()/bitmap.getWidth();
    return android.graphics.Bitmap.createScaledBitmap(bitmap, (int)(iw*scalefactor), (int)(ih*scalefactor), true);
    //return bitmap;
}

答案 8 :(得分:0)

其中一种方法是将android:adjustViewBounds =“true”设置为ImageView,并将缩放类型设置为xml文件中的“fitCenter”。 这应该按预期工作。 您也可以通过设置ImageView.adjustViewBounds(true)和ImageView.setScaleType(ScaleType.FIT_CENTER)以编程方式执行此操作。