Glide加载圆形图片和圆角图片

笔者最近工作不太忙,就来整理一下之前遇到的问题,今天整理的是Glide加载圆形图片和圆角图片,后面会陆陆续续的整理其他方面的,废话不多说,直接上代码、

实现圆角图片

package util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;


/**
 * @author han update at 2018.02.07
 */


public class GlideRoundTransform extends BitmapTransformation {

	private static float radius = 0f;

	public GlideRoundTransform(Context context) {
		this(context, 4);
	}

	public GlideRoundTransform(Context context, int dp) {
		super(context);
		this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
	}

	@Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
		return roundCrop(pool, toTransform);
	}

	private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
		if (source == null) return null;

		Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
		if (result == null) {
			result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
		}

		Canvas canvas = new Canvas(result);
		Paint paint = new Paint();
		paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
		paint.setAntiAlias(true);
		RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
		canvas.drawRoundRect(rectF, radius, radius, paint);
		return result;
	}

	@Override public String getId() {
		return getClass().getName() + Math.round(radius);
	}
}

Glide.with(context)
                    .load(MyApp.ImgUrl(bean.getShopimg()))
                    .placeholder(R.drawable.defaultshop)
                    .error(R.drawable.defaultshop)
                    .transform(new CenterCrop(context), new GlideRoundTransform(context))
                    .crossFade()
                    .override(DensityUtil.dp(context,60), DensityUtil.dp(context,60))
                    .into(((Holder) viewHolder).shopImv);

好了,是不是很简单,Glide用起来还是很方便的

猜你喜欢

转载自blog.csdn.net/wangbhan/article/details/83443826