Why is the image distorted (does not maintain proportions) in ImageView?

5

I have some images inside the folder drawable and I call them via code:

 public void inserindoImage(ImageView image,int rid,LinearLayout linear )
    {
        image.setBackgroundResource(rid);
        linear.addView(image);
    }

When you call this function, the image goes on the screen.

and stay that way

OriginalImage

IwouldliketoknowhowtomaketheimagekeeptheratioinimagemView,asyoucanseethereisadeformationintheimage.

xml

<ScrollViewandroid:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:id="@+id/scrollView">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/linearImage"
            android:orientation="horizontal">
            <!--Imagem vem aqui-->
        </LinearLayout>
    </LinearLayout>
</ScrollView>

In the case I put one, but there comes more image so the scroolView .

    
asked by anonymous 22.03.2016 / 14:43

1 answer

7

Replace image.setBackgroundResource(rid); with image.setImageResource(rid);

setBackgroundResource () assigns image to the background of the view causing it to "stretch" in order to fill it all.

Turn setImageResource () assigns the image to ImageView content, taking into account its dimensions.

In principle, whenever you create a View , you should also indicate which LayoutParams to use for it.

Change the method by insertingImage () to:

public void inserindoImage(ImageView image,int rid,LinearLayout linear )
{
    LinearLayout.LayoutParams params =
        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                      ViewGroup.LayoutParams.WRAP_CONTENT);

    image.setLayoutParams(params);
    image.setImageResource(rid);
    linear.addView(image);
}
    
24.03.2016 / 15:21