简体   繁体   中英

Set a maximum height of an image as a proportion of screen size

I have a screen in my app with a large image at the top (filling the width of the screen) and some text and buttons below it in a relative layout.

<RelativeLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".WelcomeScreenActivity"
>

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:id="@+id/imgFirstScreenImage"
    android:layout_centerHorizontal="true"
    android:src="@drawable/first_screen_image"/>

<TextView
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:text="@string/first_screen_text"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/firstScreenText"
    android:layout_below="@+id/imgFirstScreenImage"
    android:layout_centerHorizontal="true"
    android:gravity="center" />

This is working fine on newer phones, like the Nexus 5 and 5X, but on the Nexus 4 the text is partly off the bottom of the screen.

I want the image to be able to be cropped so that it will only fill a maximum of 50% of the height of the screen so that the other elements will always appear on the screen, but only if the screen size is below a certain size, so what I am looking for is some sort of fallback.

I am using different resolutions of the image in my drawables folders, but that doesn't seem to be enough in this case, it appears that the Nexus 4 is using the xhdpi version anyway. I'm very new to android though, so I could easily be mistaken, or be looking in the wrong direction entirely.

It would be more practical if you can define a certain height percentage for your screen.

Like - 70 % for the image and 30 % for the rest. You can achieve this easily with layout_weight and Linear layouts.

But if you keep focusing on your requirement, you can do as follows,

  1. Get the device height programatically.
  2. If device height < certain size, then set the imageView maximum height programatically.

Ex - imageView max height = device height / 2

Otherwise leave it as it is.

This might work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM