【问题标题】:Set Background Image to Relative Layout using Glide in Android在 Android 中使用 Glide 将背景图像设置为相对布局
【发布时间】:2015-11-28 13:05:03
【问题描述】:

如何使用 Glide 做到这一点?我想cache 图像再次使用它。提前致谢。

【问题讨论】:

    标签: layout android-glide


    【解决方案1】:

    您可以像这样在 RelativeLayout 中加载图像。我只是向您展示将图像设置为背景的难点。

    适用于 4.X 之前的 Glide 版本

    Glide.with(this).load(imageViewPath).asBitmap().into(new SimpleTarget<Bitmap>(relLayoutWidth, relLayoutHeight) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
            Drawable drawable = new BitmapDrawable(context.getResources(), resource);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                yourRelativeLayout.setBackground(drawable);
            }
        }
    });
    

    有关缓存,请参阅此页面:Caching and Cache Invalidation

    Glide v4 以后的更新:

    GlideApp.with(this).load(R.drawable.backgroundimage).into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        yourRelativeLayout.setBackground(resource);
                    }
                }
            });
    

    【讨论】:

    • 为什么需要Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.JELLY_BEAN
    • @dal102 满足我的应用特定需求
    • 没有它你会收到警告Call requires API level 16 (current min is XX): android.view.View#setBackground -> 所以这个解决方案只适用于JELLY_BEAN和更高的API
    • 现在已弃用。推荐使用 CustomViewTarget
    【解决方案2】:

    目前,在 Glide 4.9.0 版本中,您可以将相对布局的背景设置为:-

    Glide.with(MainActivity.this)
                        .load(IMAGE_URL)
                        .into(new CustomTarget<Drawable>() {
                            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                mLinearLayout.setBackground(resource);
                            }
    
                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {
    
                            }
                        });
    

    【讨论】:

      【解决方案3】:

      我认为实现它的最佳方法是使用你自己的 ViewTarget 实现,因为这个类有特定的方法可以在不同的场景中由 Glide 自动处理。

      ViewGroup 的抽象实现(LinearLayout、RelativeLayout 等)。

      public abstract class ViewGroupTarget<Z> extends ViewTarget<ViewGroup, Z> implements GlideAnimation.ViewAdapter {
      
          public ViewGroupTarget(ViewGroup view) {
              super(view);
          }
      
          /**
           * Returns the current {@link android.graphics.drawable.Drawable} being displayed in the view using
           * {@link android.widget.ImageView#getDrawable()}.
           */
          @Override
          public Drawable getCurrentDrawable() {
              return view.getBackground();
          }
      
          /**
           * Sets the given {@link android.graphics.drawable.Drawable} on the view using
           * {@link android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable)}.
           *
           * @param drawable {@inheritDoc}
           */
          @Override
          public void setDrawable(Drawable drawable) {
              view.setBackground(drawable);
          }
      
          /**
           * Sets the given {@link android.graphics.drawable.Drawable} on the view using
           * {@link android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable)}.
           *
           * @param placeholder {@inheritDoc}
           */
          @Override
          public void onLoadStarted(Drawable placeholder) {
              view.setBackground(placeholder);
          }
      
          /**
           * Sets the given {@link android.graphics.drawable.Drawable} on the view using
           * {@link android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable)}.
           *
           * @param errorDrawable {@inheritDoc}
           */
          @Override
          public void onLoadFailed(Exception e, Drawable errorDrawable) {
              view.setBackground(errorDrawable);
          }
      
          /**
           * Sets the given {@link android.graphics.drawable.Drawable} on the view using
           * {@link android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable)}.
           *
           * @param placeholder {@inheritDoc}
           */
          @Override
          public void onLoadCleared(Drawable placeholder) {
              view.setBackground(placeholder);
          }
      
          @Override
          public void onResourceReady(Z resource, GlideAnimation<? super Z> glideAnimation) {
      
              this.setResource(resource);
          }
      
          protected abstract void setResource(Z resource);
      
      }
      

      具体实现,本例为LinearLayout。

      public class LinearLayoutTarget extends ViewGroupTarget<Bitmap> {
      
          private Context context;
      
          public LinearLayoutTarget(Context context, LinearLayout linearLayout) {
      
              super(linearLayout);
      
              this.context = context;
          }
      
          /**
           * Sets the {@link android.graphics.Bitmap} on the view using
           * {@link android.widget.ImageView#setImageBitmap(android.graphics.Bitmap)}.
           *
           * @param resource The bitmap to display.
           */
          @Override
          protected void setResource(Bitmap resource) {
      
              view.setBackground(new BitmapDrawable(context.getResources(), resource));
          }
      
      }
      

      合作。

      Glide.with(this.getApplicationContext())
                      .load(R.drawable.your_image)
                      .asBitmap()
                      .into(new LinearLayoutTarget(this.getApplicationContext(), (LinearLayout) yourLinearLayoutInstanceHere));
      

      或者更简单的工作没有位图。

      具体实现。

      public class LinearLayoutTarget extends ViewGroupTarget<Drawable> {
      
          public LinearLayoutTarget(LinearLayout linearLayout) {
      
              super(linearLayout);
          }
      
          /**
           * Sets the {@link android.graphics.Bitmap} on the view using
           * {@link android.widget.ImageView#setImageBitmap(android.graphics.Bitmap)}.
           *
           * @param resource The bitmap to display.
           */
          @Override
          protected void setResource(Drawable resource) {
      
              view.setBackground(resource);
          }
      
      }
      

      合作。

      Glide.with(this.getApplicationContext())
                      .load(R.drawable.your_image)
                      .into(new LinearLayoutTarget((LinearLayout) yourLinearLayoutInstanceHere));
      

      【讨论】:

      • 其实应该是ViewGroupTarget&lt;GlideDrawable&gt; 而不是Drawable 很重要的区别
      【解决方案4】:

      (SimpleTarget 类已弃用,因此使用 CustomTarget 类加载图像)

      您可以像这样在 RelativeLayout 中加载图像。我只是向您展示将图像设置为背景的难点。

      适用于 4.X 之前的 Glide 版本(未弃用)

      Glide.with(this).load(ServiceGenerator.BASE_URL + url).into(new CustomTarget<Drawable>() {
                  @Override
                  public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                      yourRelativeLayout.setBackground(resource);
                  }
      
                  @Override
                  public void onLoadCleared(@Nullable Drawable placeholder) {
                  }
      
              });
      

      【讨论】:

        【解决方案5】:

        这是 Kotlin 的代码

        • Glide 4.9.x
        • 由于 SimpleTarget 已被弃用,我们现在必须使用 CustomTarget,如下所示
        Glide.with(this).load(UCrop.getOutput(data)).into(object : 
                                CustomTarget<Drawable>() {
                                override fun onLoadCleared(placeholder: Drawable?) {
                                    TODO("Not yet implemented")
                                }
        
                                override fun onResourceReady(
                                    resource: Drawable,
                                    transition: Transition<in Drawable>?
                                ) {
                                    ib_pet_profile_image.background=resource
                                }
        
                            })
        

        【讨论】:

          【解决方案6】:
          Glide.with(ctx).asBitmap().load(url).centerCrop().into(object: CustomTarget<Bitmap>(){
                      override fun onLoadCleared(placeholder: Drawable?) {
                      }
          
                      override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                          val wRatio = view.width/resource.width.toFloat()
                          val hRatio = view.height / resource.height.toFloat()
          
                          val minRatio = min(wRatio,hRatio)
          
                          val destBitmap = Bitmap.createScaledBitmap( resource,(resource.width*minRatio).toInt(), (resource.height*minRatio).toInt(),false)
                         view.background = BitmapDrawable(resources,destBitmap)
                      }
                  })
          

          这对我有用

          PS:位图过大会报错

          java.lang.RuntimeException: Canvas: 试图绘制过大的位图。

          所以你最好像我在上面的代码中那样缩放该位图

          【讨论】:

            【解决方案7】:

            谢谢大家。你所有的答案都帮助了我。我还通过 Glide 的官方文档找到了有用的解决方案。我已经切换到 Glide App Module 以便对其进行通用使用。

            https://medium.com/@nuhkocaa/manage-all-your-glides-in-a-single-class-with-glidemodule-on-android-4856ee4983a1

            【讨论】:

              【解决方案8】:

              我需要设置ImageView 的背景(这样我可以将前景设置为不同的图像)。 我最终找到了https://github.com/bumptech/glide/issues/938#issuecomment-176150770,但这有点过时了。通过实验,我将其更改为以下内容以与 Glide 4 一起使用(类似于此处的其他一些答案):

              /** @see ImageViewTarget
               */
              abstract class ViewBackgroundTarget<Z>(view: View) : CustomViewTarget<View?, Z>(view) {
                  override fun onLoadFailed(errorDrawable: Drawable?) {
                  }
              
                  override fun onResourceCleared(placeholder: Drawable?) {
                      // This line is ESSENTIAL or else there will be occasional crashes like:
                      // "java.lang.NullPointerException: Attempt to invoke virtual method 
                      // 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference"
                      view!!.background = placeholder
                  }
              }
              
              /** @see BitmapImageViewTarget
               */
              class BitmapViewBackgroundTarget(view: View) : ViewBackgroundTarget<Bitmap>(view) {
                  override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                      view!!.background = BitmapDrawable(view.resources, resource)
                  }
              }
              
              /** @see DrawableImageViewTarget
               */
              class DrawableViewBackgroundTarget(view: View) : ViewBackgroundTarget<Drawable>(view) {
                  override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                      view!!.background = resource
                      if (resource is GifDrawable) {
                          resource.setLoopCount(LOOP_FOREVER)
                          resource.start()
                      }
                  }
              }
              

              使用它

              Glide.with(myImageView)
                      .load(imageUrl)
                      .into(DrawableViewBackgroundTarget(myImageView))
              

              我认为这对于 RelativeLayout 或其他 View 类型也可以轻松工作。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-11-16
                • 2014-01-24
                • 1970-01-01
                • 1970-01-01
                • 2016-03-23
                • 1970-01-01
                相关资源
                最近更新 更多