Android中經常會遇到對圖片進行二次處理,例如加圓角,或者顯示圓形圖片 ...
Android中經常會遇到對圖片進行二次處理,例如加圓角,或者顯示圓形圖片
方法一:
通過第三方框架Glide實現圖片顯示有圓角,有三種寫法如下:
1.1,第一種實現:
RequestOptions options = new RequestOptions().error(R.drawable.img_load_failure).bitmapTransform(new RoundedCorners(30));//圖片圓角為30
Glide.with(this).load(URL) //圖片地址
.apply(options)
.into(ImagView);
1.2,第二種實現:
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_launcher_background);
requestOptions.circleCropTransform();
requestOptions.transforms( new RoundedCorners(30));
Glide.with(this).load(URL) //圖片地址
.apply(options)
.into(ImagView);
1.3,第三種實現:
RequestOptions options = new RequestOptions().centerCrop() .transform(new RoundTransform(this,30));
Glide.with(this).load(URL) //圖片地址
.apply(options)
.into(ImagView);
public class RoundTransform extends BitmapTransformation {
private static float radius = 0f;
public RoundTransform(Context context) {
this(context, 4);
}
public RoundTransform(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) {
Bitmap bitmap = TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight);
return roundCrop(pool, bitmap);
}
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);
} 無錫人流多少錢 http://www.bhnfkyy.com
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;
}
public String getId() {
return getClass().getName() + Math.round(radius);
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {
}
}