Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Set a border around an ImageView

I have a cell with a fixed width and height, let it be 100x100px. Inside that cell I want to display an ImageView with a border around.
My first idea was to put a background resource to the ImageView, and add a padding of 1dp to create the border effect:

<LinearLayout         android:layout_width="100dp"         android:layout_height="100dp" >      <ImageView         android:id="@+id/imageView"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:background="@drawable/image_border"         android:padding="1dp"         android:src="@drawable/test_image" />  </LinearLayout> 

Apparently this should work, but it doesn't, or at least not as expected.
The problem is that the ImageView background fills the entire 100x100px cell's space, thus, if the image's width is less than 100px, then the top and bottom border will appear larger.

Notice the yellow border, I need it to be exactly 1px around the ImageView:

enter image description here

Any help, idea, suggestion of any kind is much, much appreciated.

like image 757
Andy Res Avatar asked Sep 24 '12 20:09

Andy Res


People also ask

How to set frame on image in android?

Step 1: Download and install Photo Frame app for your device. Step 2: Launch the app and allow the app to access the media files on your device. Step 3: Tap on Simple layouts option which is at the bottom left corner of the screen. Step 4: Scroll through the list of options and select the frame you like.

What is adjustViewBounds?

android:adjustViewBounds—If set to true, the attribute adjusts the bounds of the ImageView control to maintain the aspect ratio of the image displayed through it.


Video Answer


2 Answers

If you put the padding=1 and the background color in the LinearLayout, you'll have a 1px yellow border.

like image 94
Christine Avatar answered Sep 20 '22 01:09

Christine


Here is what worked for me...

<!-- @drawable/image_border --> <shape xmlns:android="http://schemas.android.com/apk/res/android">   <solid android:color="@color/colorPrimary"/>   <stroke android:width="1dp" android:color="#000000"/>   <padding android:left="1dp" android:top="1dp" android:right="1dp" android:bottom="1dp"/> </shape>  <ImageView   android:layout_width="300dp"   android:layout_height="300dp"   android:layout_gravity="center"   android:padding="1dp"   android:cropToPadding="true"   android:scaleType="centerCrop"   android:background="@drawable/image_border"/> 

Here it the result that I get with an viewpager and imageview with a border.

Example imageview with border 1dp black.

like image 41
Ray Hunter Avatar answered Sep 21 '22 01:09

Ray Hunter