Kinjal Patel
Kinjal Patel

Reputation: 105

Android add border image to ImageView

Is it possible to add a bitmap as border of an ImageView in android dynamically in Java?

I have already tried the following:

Image view in XML and border as shape the result is wrong I want to add bitmap in border.

Upvotes: 4

Views: 8757

Answers (4)

abdul rehman
abdul rehman

Reputation: 260

The simplest solution I found recently. Try to use material theme in your app. Use "Theme.MaterialComponents.Light"

Then use image view inside and material card view.

        <com.google.android.material.card.MaterialCardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardBackgroundColor="@color/white"
            app:cardCornerRadius="8dp"
            app:cardElevation="0dp"
            app:strokeColor="@color/colorPrimary"
            app:strokeWidth="1dp">
              
              <ImageView/>//define you image view hear
       
        </com.google.android.material.card.MaterialCardView>

With property stokeColor and strokeWidth you can have border on an image view and make it dynamic.

Upvotes: 1

DEEz
DEEz

Reputation: 191

you can use 9 patch in andorid studio to make an image a border!

i was finding a solution but i did not find any so i skipped that part

then i go to the google images of firebase assets and i accidentaly discovered that they use 9patch

9patch in action

heres the link: https://developer.android.com/studio/write/draw9patch you just need to drag where the edges are

its just like boder edge in unity

Upvotes: 0

Tommy
Tommy

Reputation: 179

The simple way:

A drawable for ImageView's attr that android:foreground

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">


    <stroke android:width="1px" android:color="#ff0000" />

    <solid android:color="@android:color/transparent"/>

</shape>

Then XML,

<ImageView
    android:id="@+id/unreserved_head_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:foreground="@drawable/shape_border"
    />

Upvotes: 3

daemmie
daemmie

Reputation: 6460

You have got multiple options:

  1. Place an other View with the border (also imageview) above your Imageview. Thay might be the simples solution. Just add an other view to your xml and make sure they are overlapping. (Use for example a Relative or FrameLayout as container)

  2. Use a Layer List and draw a shape above a Bitmap and add that to your ImageView

  3. Write a custom ImageView and use the Canvas to draw the Border in the overwritten onDraw method. E.g. canvas.drawRect(...) its pretty straightforward.

Upvotes: 2

Related Questions