Search code examples
androidimageviewnine-patch

Centering an image, horizontally


I'm just starting on my first Android app. I'm working in Android Studio, and my initial problem is to display a customer logo across the top of the first page.

I've figured out how to turn the logo into a .9.png, and to load it into the project at the various required resolutions using the android-drawable-importer plugin.

Now my problem is simply getting the image to scale properly, across my display.

Currently, I'm playing with a LinearLayout, with an ImageView taking up the top area of the display:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="12"
    >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:src="@drawable/mylogo"
        />

    <!-- ... -->

</LinearLayout>

With that, my logo takes up the top 1/6th of the display, centered horizontally, but it's not stretching to fill the full width of the display. If I add android:scaleType="fitXY", it scales to fill horizontally, but it also scales vertically, resulting in my not seeing the top and bottom of the logo.

Is there a way of displaying an image so that it fits vertically, and fills horizontally?


I'm editing this, to expand its scope, a bit. It might be that I'm too focused on making a 9-patch work, and that there are simpler solutions to my problem.

What I need is pretty simple - I want a logo displayed in the top area of the page, centered horizontally, with the logo not distorted by x- or y-axis scaling, but with the background color extending to the edges of the display, horizontally.

If a nine-patch won't do this, perhaps something else will.


Solution

  • How about using a logo with a transparent background and then just set the android:background of your ImageView to the color you need? That way you have higher control of the logo display?

    Also, have you tried experimenting with other scale types?:

    Try setting the android:scaleType="fitCenter" and your image should be displayed centered in parent and also scaled to fill as much as possible of the available space.

    If the image is still incorrectly scaled, you can also set the android:adjustViewVounds parameter in order for it to better fit your needs