Search code examples
androidimageviewandroid-relativelayoutscalingbounds

Android ImageView scaling conflict


I am creating ImageView in code:

ImageView vlogo = new ImageView(v.getContext());
        RelativeLayout.LayoutParams vlogoParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        vlogoParams.addRule(RelativeLayout.ALIGN_TOP,tv_visitor.getId());
        vlogoParams.addRule(RelativeLayout.ALIGN_LEFT, tv_visitor.getId());
        vlogoParams.addRule(RelativeLayout.ALIGN_BOTTOM, tv_visitor.getId());
        vlogo.setLayoutParams(vlogoParams);
        vlogo.setImageResource(R.drawable.star);
        rl.addView(vlogo);

The image is "scaled" by aligning it to TOP and BOTTOM of previously created tv_visitor view (that has been added to relative layout). But I asume that it isn't layedout yet(?). .requestLayout just before this code doesn't change a thing. Picture

By doing that I'm setting ImageView's height to the height of tv_visitor view. Which is OK. However the width seems to stay original.

And here comes the problem. The width stays not scaled. The way I do that is making .setAdjustViewBounds(true); not working. How should I proceed then?

As requested in comments I provide more info:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/news_scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff000000"
    android:scrollbars="none">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/fragment_news2">
    <View
        android:id="@+id/anchor_n"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#ffbb00"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" />
</RelativeLayout>
</ScrollView>

The View is passed as an parameter and layout is gotten by:

RelativeLayout rl = (RelativeLayout) v.findViewById(R.id.fragment_news2);

Solution

  • The problem is due to the scaling of Imageview, since by default imageview is using ImageView.ScaleType.FIT_CENTER. As per the documentation FIT_CENTER performs the following operation:

    Compute a scale that will maintain the original src aspect ratio, but will also ensure that src fits entirely inside dst. At least one axis (X or Y) will fit exactly. The result is centered inside dst.

    Since the Image is resized and centered, you are seeing extra spaces on both left and right side. To avoid that set ScaleType to ImageView.ScaleType.FIT_END which in turn aligns the result to the right will solve the problem.

    vlogo.setScaleType(ImageView.ScaleType.FIT_END);