I want to have fixed size box 120x180 dp that contains a picture with correct aspect ratio and a border painted around it.
XML:
<android.support.constraint.ConstraintLayout
android:layout_width="120dp"
android:layout_height="180dp"
app:layout_gravity="center">
<ImageView
android:id="@+id/picture"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@drawable/game_border"
app:srcCompat="@drawable/pic_lion"
android:scaleType="centerInside" />
Game_border layout:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#55111111" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
<corners android:radius="6dp" />
</shape>
</item>
</layer-list>
This scaleType
setting works fine because it fill complete tile inner and background is not overriden. But to demonstrate incorrect aspect ratio I have increased top margin. See picture below. I tried remaining values but they either paint over the border or do not fill complete inner part.
How can I have the tile that has the border around a part of the picture with the right aspect ratio? The picture can be cut. I think that this technique is called center crop. I found it in the Picasso library.
FitXY deforms picture:
Manually painted picture when I cropped picture while preserving aspect ratio. Sorry, it looks ugly but bounty ends very soon.
Bjorn's answer:
Rahul answer does not have bottom border
<ImageView
android:id="@id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
scaleType="fitCenter" (default when omitted)
will make it as wide as the parent allows and up/down-scale as needed keeping aspect ratio.
scaleType="centerInside"
if the intrinsic width of src is smaller than parent width will center the image horizontally
f the intrinsic width of src is larger than parent width will make it as wide as the parent allows and down-scale keeping aspect ratio.
It doesn't matter if you use android:src
or ImageView.setImage*
.key is
android:adjustViewBounds
Or Using the CardView also you can make rounded corners for imageView.
<android.support.v7.widget.CardView
android:layout_width="120dp"
android:layout_height="180dp"
android:layout_gravity="center"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="6dp"
app:cardCornerRadius="@dimen/_5dp"
app:cardBackgroundColor="#D3D3D3"
app:cardPreventCornerOverlap="false"
card_view:cardPreventCornerOverlap="false">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:background="@drawable/image"
android:scaleType="fitXY" />
</android.support.v7.widget.CardView>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With