从URI加载图像作为布局背景

问题描述 投票:6回答:3

我使用Picasso将我公司的CDN中的图像加载到ImageView

ImageView imgView;
//...
Picasso.with(context).load(Uri.parse(url)).into(imgView);

但现在我需要加载图像作为布局背景:

RelativeLayout theLayout;
//...
Picasso.with(context).load(Uri.parse(url)).into(...);

毕加索有可能吗?如果没有,我应该使用ImageView而不是Relativelayout

android picasso
3个回答
1
投票
 Picasso.with(getActivity()).load(your url).into(new Target(){

  @Override
  public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
     yourlayout.setBackground(new BitmapDrawable(context.getResources(), bitmap));
  }

编辑:

您可能还需要覆盖以下方法

@Override
  public void onBitmapFailed(final Drawable errorDrawable) {
      Log.e("TAG", "Failed");
  }

  @Override
  public void onPrepareLoad(final Drawable placeHolderDrawable) {
      Log.e("TAG", "Prepare Load");
  }      
}

3
投票

您可以使用滑动下载位图并将其设置为任何布局的背景。

Glide
        .with(getApplicationContext())
        .load("https://www.google.es/images/srpr/logo11w.png")
        .asBitmap()
        .into(new SimpleTarget<Bitmap>(100,100) {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
              Drawable dr = new BitmapDrawable(resource);
             theLayout.setBackgroundDrawable(dr);
                  // Possibly runOnUiThread()
            }
        });

但更好的方法是在imageView上使用relativelayout并使其成为match_parent并在此imageview上显示图像。这将帮助您直接使用glide或picaso在图像视图中加载图像而不会出现内存错误。


1
投票

是。你可以使用Picasso。请检查以下代码:

Picasso.with(getActivity()).load(Uri.parse(url)).into(new Target(){

  @Override
  public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
     relativeLayout.setBackground(new BitmapDrawable(context.getResources(), bitmap));
  }

  @Override
  public void onBitmapFailed(final Drawable errorDrawable) {
      Log.d("TAG", "FAILED");
  }

  @Override
  public void onPrepareLoad(final Drawable placeHolderDrawable) {
      Log.d("TAG", "Prepare Load");
  }      
})
© www.soinside.com 2019 - 2024. All rights reserved.