安卓笔记侠

专注安卓开发

导航

Picasso通过URL获取--用户头像的圆形显示

1.设置布局属性:

<ImageView
    android:scaleType="fitXY"/>

2.BitmapUtils类-- 得到指定圆形的Bitmap对象

public static Bitmap circleBitmap(Bitmap source) {
    //获取Bitmap的宽度
    int width = source.getWidth();
    //以Bitmap的宽度值作为新的bitmap的宽高值。
    Bitmap bitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
    //以此bitmap为基准,创建一个画布
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    //在画布上画一个圆
    canvas.drawCircle(width / 2, width / 2, width / 2, paint);

    //设置图片相交情况下的处理方式
    //setXfermode:设置当绘制的图像出现相交情况时候的处理方式的,它包含的常用模式有:
    //PorterDuff.Mode.SRC_IN 取两层图像交集部分,只显示上层图像
    //PorterDuff.Mode.DST_IN 取两层图像交集部分,只显示下层图像
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    //在画布上绘制bitmap
    canvas.drawBitmap(source, 0, 0, paint);

    return bitmap;

}

3.BitmapUtils类--压缩图片

//实现图片的压缩处理
//设置宽高必须使用浮点型,否则导致压缩的比例:0
public static Bitmap zoom(Bitmap source,float width ,float height){

    Matrix matrix = new Matrix();
    //图片的压缩处理
    matrix.postScale(width / source.getWidth(),height / source.getHeight());

    Bitmap bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
    return bitmap;
}

4.根据user.getImageurl()显示圆形图像

//使用Picasso联网获取图片
Picasso.with(this.getActivity()).load(user.getImageurl()).transform(new Transformation() {
    @Override
    public Bitmap transform(Bitmap source) {//下载以后的内存中的bitmap对象
        //压缩处理
        Bitmap bitmap = BitmapUtils.zoom(source, UIUtils.dp2px(62),UIUtils.dp2px(62));
        //圆形处理
        bitmap = BitmapUtils.circleBitmap(bitmap);
        //回收bitmap资源
        source.recycle();
        return bitmap;
    }

    @Override
    public String key() {
        return "";//需要保证返回值不能为null。否则报错
    }
}).into(ivMeIcon);

  

  

  

posted on 2017-06-27 23:59  安卓笔记侠  阅读(408)  评论(1编辑  收藏  举报