Search code examples
androidimageviewscrollviewscale

How to scale small imageview to fill large scrollview?


How do you create a layout with a screen-filling scrollview that has a small image in an imageview scaled to fit the whole scrollview and be scrollable? eg. A 720x1280 display has a full-screen scrollview (fill_parent). Inside is a linearlayout (fill_parent). In that is a 300x900 bitmap in an imageview that is upscaled to 720x2160, fills the screen width and exceeds the vertical bounds, and can be scrolled up/down in the scrollview.

The solution should work for all screen sizes to support multiple devices from mobiles to tablets.


Solution

  • This works for me:

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    
            <ImageView
                android:layout_width="720dp"
                android:layout_height="2160dp"
                android:src="@drawable/image"
                android:scaleType="fitXY"/>
    
        </LinearLayout>
    
    </ScrollView>
    

    If you need to make this work for any screen size do it programmatically:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        imageView = (ImageView) findViewById(R.id.imageView);
    
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;
    
        imageView.getLayoutParams().width = width;
    }