Picasso使用教程

Introduction

Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application—often in one line of code!android

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Many common pitfalls of image loading on Android are handled automatically by Picasso:app

  • Handling ImageView recycling and download cancelation in an adapter.
  • Complex image transformations with minimal memory use.
  • Automatic memory and disk caching.

Sample application screenshot.

Features

ADAPTER DOWNLOADS

Adapter re-use is automatically detected and the previous download canceled.ide

@Override public void getView(int position, View convertView, ViewGroup parent) {
  SquaredImageView view = (SquaredImageView) convertView;
  if (view == null) {
    view = new SquaredImageView(context);
  }
  String url = getItem(position);

  Picasso.with(context).load(url).into(view);
}

IMAGE TRANSFORMATIONS

Transform images to better fit into layouts and to reduce memory size.this

Picasso.with(context)
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

You can also specify custom transformations for more advanced effects.url

public class CropSquareTransformation implements Transformation {
  @Override public Bitmap transform(Bitmap source) {
    int size = Math.min(source.getWidth(), source.getHeight());
    int x = (source.getWidth() - size) / 2;
    int y = (source.getHeight() - size) / 2;
    Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
    if (result != source) {
      source.recycle();
    }
    return result;
  }

  @Override public String key() { return "square()"; }
}

Pass an instance of this class to the transform method.spa

PLACE HOLDERS

Picasso supports both download and error placeholders as optional features.code

Picasso.with(context)
    .load(url)
    .placeholder(R.drawable.user_placeholder)
    .error(R.drawable.user_placeholder_error)
    .into(imageView);

A request will be retried three times before the error placeholder is shown.orm

RESOURCE LOADING

Resources, assets, files, content providers are all supported as image sources.three

Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);

DEBUG INDICATORS

For development you can enable the display of a colored ribbon which indicates the image source. Call setIndicatorsEnabled(true)on the Picasso instance.ssl

Debug ribbon indicators

相關文章
相關標籤/搜索