Search code examples
androidimageandroid-layoutscale

Scale images in android relative to screen width


I have a layout with two images:

  • one that should strech to the screen width
  • one above it that should scale to the same proportion the first one was automaticaly scaled (relative to the original image size)

More specific: the two images are slices of the same image, and therefore some details inside them should match.
Can I make this in XML?

If I cannot do it through XML, maybe I could prescale the graphics. In this case, how should I prescale them?


Solution

  • This is a bit of a hack, but it would allow you to do this in xml.

    If you know that, for example, the top image is X% of the size of the bottom one, then you can use LinearLayout's layout_weight to position and size the top image in terms of percentage of the screen:

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <ImageView android:id="@+id/left_filler" android:layout_weight="20"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <ImageView android:id="@+id/top_image" android:layout_weight="50"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <ImageView android:id="@+id/right_filler" android:layout_weight="30"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    </LinearLayout>
     ... bottom image

    The above would size top_image at 50% of the screen with an offset of 20% from the left. As long as top_image is 50% the size of bottom_image, this will keep similar scale.

    Alternatively, the "right" way to do this is probably to override onDraw() in a custom view and use canvas drawing methods.