Android                
            피카소
        
        
            
    수색…
소개
Picasso 는 Android 용 이미지 라이브러리입니다. 스퀘어 가 만들고 관리합니다. 외부 위치에서 이미지를 표시하는 프로세스를 단순화합니다. 라이브러리는 초기 HTTP 요청부터 이미지 캐싱까지 프로세스의 모든 단계를 처리합니다. 대부분의 경우이 깔끔한 라이브러리를 구현하려면 몇 줄의 코드 만 있으면됩니다.
비고
Android 프로젝트에 Picasso 라이브러리 추가
공식 문서에서 :
요람.
dependencies {
 compile "com.squareup.picasso:picasso:2.5.2"
}
 메이븐 :
<dependency>
  <groupId>com.squareup.picasso</groupId>
  <artifactId>picasso</artifactId>
  <version>2.5.2</version>
</dependency>
        자리 표시 자 및 오류 처리
Picasso는 다운로드 및 오류 자리 표시자를 선택적 기능으로 지원합니다. 또한 다운로드 결과를 처리하기위한 콜백을 제공합니다.
Picasso.with(context)
  .load("YOUR IMAGE URL HERE")
  .placeholder(Your Drawable Resource)   //this is optional the image to display while the url image is downloading
  .error(Your Drawable Resource)         //this is also optional if some error has occurred in downloading the image this image would be displayed
  .into(imageView, new Callback(){
     @Override
        public void onSuccess() {}
        @Override
        public void onError() {}
   });
 오류 표시 자리가 표시되기 전에 요청이 세 번 재 시도됩니다.
크기 조정 및 회전
Picasso.with(context)
 .load("YOUR IMAGE URL HERE")        
 .placeholder(DRAWABLE RESOURCE)   // optional        
 .error(DRAWABLE RESOURCE)         // optional        
 .resize(width, height)            // optional        
 .rotate(degree)                   // optional        
 .into(imageView);
        피카소와 원형 아바타
다음은 얇은 테두리가 추가 된 원본을 기반으로 한 Picasso Circle Transform 클래스의 예입니다. 스태킹을위한 선택적 구분 기호에 대한 기능도 포함되어 있습니다.
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import com.squareup.picasso.Transformation;
public class CircleTransform implements Transformation {
    boolean mCircleSeparator = false;
    public CircleTransform(){
    }
    public CircleTransform(boolean circleSeparator){
        mCircleSeparator = circleSeparator;
    }
    @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 squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
        if (squaredBitmap != source) {
            source.recycle();
        }
        Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
        Canvas canvas = new Canvas(bitmap);
        BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);
        paint.setShader(shader);
        float r = size/2f;
        canvas.drawCircle(r, r, r-1, paint);
        // Make the thin border:
        Paint paintBorder = new Paint();
        paintBorder.setStyle(Style.STROKE);
        paintBorder.setColor(Color.argb(84,0,0,0));
        paintBorder.setAntiAlias(true);
        paintBorder.setStrokeWidth(1);
        canvas.drawCircle(r, r, r-1, paintBorder);
        // Optional separator for stacking:
        if (mCircleSeparator) {
            Paint paintBorderSeparator = new Paint();
            paintBorderSeparator.setStyle(Style.STROKE);
            paintBorderSeparator.setColor(Color.parseColor("#ffffff"));
            paintBorderSeparator.setAntiAlias(true);
            paintBorderSeparator.setStrokeWidth(4);
            canvas.drawCircle(r, r, r+1, paintBorderSeparator);
        }
        squaredBitmap.recycle();
        return bitmap;
    }
    @Override
    public String key() {
        return "circle";
    }
}
  이미지를로드 할 때 이미지 컨텍스트를 사용하는 방법입니다 ( this 컨텍스트는 Activity Context이고 url 은로드 할 이미지 url 이있는 String 임). 
ImageView ivAvatar = (ImageView) itemView.findViewById(R.id.avatar);
Picasso.with(this).load(url)
    .fit()
    .transform(new CircleTransform())
    .into(ivAvatar);
 결과:
 구분 기호와 함께 사용하려면 최상위 이미지의 생성자에 true 를 지정합니다. 
ImageView ivAvatar = (ImageView) itemView.findViewById(R.id.avatar);
Picasso.with(this).load(url)
    .fit()
    .transform(new CircleTransform(true))
    .into(ivAvatar);
 결과 (FrameLayout의 2 개의 ImageView) :
Picasa에서 캐시 사용 중지
Picasso.with(context)
.load(uri)
.networkPolicy(NetworkPolicy.NO_CACHE)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.placeholder(R.drawable.placeholder)
.into(imageView);
        외부 저장소에서 이미지로드 중
String filename = "image.png";
String imagePath = getExternalFilesDir() + "/" + filename;
Picasso.with(context)
    .load(new File(imagePath))
    .into(imageView);
        Picasso를 사용하여 이미지를 비트 맵으로 다운로드
 Picasso 사용하여 Bitmap 이미지를 다운로드하려면 다음 코드를 사용하십시오. 
Picasso.with(mContext)
        .load(ImageUrl)
        .into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
               // Todo: Do something with your bitmap here
            }
            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }
            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        });
        Picasso를 사용하여 이미지 요청 취소
경우에 따라 다운로드가 완료되기 전에 Picasso에서 이미지 다운로드 요청을 취소해야합니다.
이는 이미지 다운로드가 완료되기 전에 부모보기가 다른보기로 전환 된 경우와 같이 여러 가지 이유로 발생할 수 있습니다.
 이 경우 cancelRequest() 메소드를 사용하여 이미지 다운로드 요청을 취소 할 수 있습니다. 
ImageView imageView; 
//......
Picasso.with(imageView.getContext()).cancelRequest(imageView);
        Picasa를 Html.fromHtml 용 ImageGetter로 사용
Picasa 를 Html.fromHtml 용 ImageGetter로 사용
public class PicassoImageGetter implements Html.ImageGetter {
private TextView textView;
private Picasso picasso;
public PicassoImageGetter(@NonNull Picasso picasso, @NonNull TextView textView) {
    this.picasso = picasso;
    this.textView = textView;
}
@Override
public Drawable getDrawable(String source) {
    Log.d(PicassoImageGetter.class.getName(), "Start loading url " + source);
    BitmapDrawablePlaceHolder drawable = new BitmapDrawablePlaceHolder();
    picasso
            .load(source)
            .error(R.drawable.connection_error)
            .into(drawable);
    return drawable;
}
private class BitmapDrawablePlaceHolder extends BitmapDrawable implements Target {
    protected Drawable drawable;
    @Override
    public void draw(final Canvas canvas) {
        if (drawable != null) {
            checkBounds();
            drawable.draw(canvas);
        }
    }
    public void setDrawable(@Nullable Drawable drawable) {
        if (drawable != null) {
            this.drawable = drawable;
            checkBounds();
        }
    }
    private void checkBounds() {
        float defaultProportion = (float) drawable.getIntrinsicWidth() / (float) drawable.getIntrinsicHeight();
        int width = Math.min(textView.getWidth(), drawable.getIntrinsicWidth());
        int height = (int) ((float) width / defaultProportion);
        if (getBounds().right != textView.getWidth() || getBounds().bottom != height) {
            setBounds(0, 0, textView.getWidth(), height); //set to full width
            int halfOfPlaceHolderWidth = (int) ((float) getBounds().right / 2f);
            int halfOfImageWidth = (int) ((float) width / 2f);
            drawable.setBounds(
                    halfOfPlaceHolderWidth - halfOfImageWidth, //centering an image
                    0,
                    halfOfPlaceHolderWidth + halfOfImageWidth,
                    height);
            textView.setText(textView.getText()); //refresh text
        }
    }
    //------------------------------------------------------------------//
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        setDrawable(new BitmapDrawable(Application.getContext().getResources(), bitmap));
    }
    @Override
    public void onBitmapFailed(Drawable errorDrawable) {
        setDrawable(errorDrawable);
    }
    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
        setDrawable(placeHolderDrawable);
    }
    //------------------------------------------------------------------//
}
}
 사용법은 간단합니다.
Html.fromHtml(textToParse, new PicassoImageGetter(picasso, textViewTarget), null);
        먼저 오프라인 디스크 캐시를 시도한 다음 온라인 상태로 전환하고 이미지를 가져옵니다.
먼저 OkHttp를 앱 모듈의 gradle 빌드 파일에 추가합니다.
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.0.2'
 그런 다음 응용 프로그램을 확장하는 클래스를 만듭니다.
import android.app.Application;
import com.squareup.picasso.OkHttpDownloader;
import com.squareup.picasso.Picasso;
public class Global extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Picasso.Builder builder = new Picasso.Builder(this);
        builder.downloader(new OkHttpDownloader(this,Integer.MAX_VALUE));
        Picasso built = builder.build();
        built.setIndicatorsEnabled(true);
        built.setLoggingEnabled(true);
        Picasso.setSingletonInstance(built);
    }
}
 다음과 같이 Manifest 파일에 추가하십시오.
<application
        android:name=".Global"
        .. >
</application>
 일반적인 사용법
Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
    @Override
    public void onSuccess() {
        //Offline Cache hit
    }
    @Override
    public void onError() {
        //Try again online if cache failed
        Picasso.with(getActivity())
                .load(imageUrl)
                .error(R.drawable.header)
                .into(imageView, new Callback() {
            @Override
            public void onSuccess() {
                 //Online download
            }
            @Override
            public void onError() {
                Log.v("Picasso","Could not fetch image");
            }
        });
    }
});
 
    
    
    
    
    
