Ankita Jaiswal
Ankita Jaiswal

Reputation: 21

While setting background Image to linear layout using glide, it appears stretched

How to preserve aspect ratio/scale of image while trying to set it as background image to LinearLayout in Android using Glide?

Hi there, I am new to Android developement.

What I want to achieve is this:

I have a Linear Layout component and I want to set an image covering one-third of the background and two-thirds with a solid color.

Problem:

the image I am passing already has width as one-third of linearLayout width, but using the below code makes it stretch in the entire available width of linearLayout and the color layer comes on top of it in two-third to area. I want the image to maintain its original aspect ratio/scale (if they are the correct terms to be used here. apologies, in case they are incorrect.)

Code: presenter.kt

val linearLayout = findViewByid(R.id.myLinearLayout)

Glide.with(linearLayout.context)
    .asBitmap()
    .load(R.drawable.backgroundimage)
    .into(
       object: CustomTarget<Bitmap>() {
            override fun onResourceReady(resource : Bitmap, transition: Transition<? super Bitmap>?) {
              val colorDrawable = ColorDrawable(Color.GREY)      
              val imageDrawable = Bitmap(resource)
              val layerDrawable = LayerDrawable(arrayOf(imageDrawable, colorDrawable))
              layerDrawable.setLayerInset(1, linearLayout.width / 3, 0, 0 , 0)
              linearLayout.setBackground(resource);
            }
        });

layout.xml

<LinearLayout
  android:id="@+id/myLinearLayout"
  android:orientation="horizontal"
  android:layout_height="wrap_content"
  android:layout_width="match_parent">

I have also tried some hacks I found in google like:

Nothing worked out.

Will appreciate any help or directions. Thanks in advance.

Upvotes: 0

Views: 34

Answers (0)

Related Questions