最近項目中有顯示數據的需求,圓角父控件中最左端放置圖片,此時顯示起來圖片的直角蓋住了父控件的圓角,故需要對圖片進行圓角處理後再顯示。
網上大多數都是通過實現Transformation,在transform方法中進行自定義處理,後來我發現Glide中的自帶的設置圓形圖片的RoundedCorners類,借鑑此類可以通過官方提供的TransformationUtils工具類來實現,具體實現如下:
public class RoundRadiusTransform extends BitmapTransformation {
// 此處用實際類的完整路徑
private static final String ID = "com.xxx.xxx.xxxx.xxx.RoundRadiusTransform";
private static final byte[] ID_BYTES = ID.getBytes(CHARSET);
private final int roundingRadius;
private boolean isLeftTop, isRightTop, isLeftBottom, isRightBottom;
private static RoundRadiusTransform mInstance;
public RoundRadiusTransform(int roundingRadius) {
this.roundingRadius = roundingRadius;
}
/**
* 需要設置圓角的部分
*
* @param leftTop 左上角
* @param rightTop 右上角
* @param leftBottom 左下角
* @param rightBottom 右下角
*/
public void setNeedCorner(boolean leftTop, boolean rightTop, boolean leftBottom, boolean rightBottom) {
isLeftTop = leftTop;
isRightTop = rightTop;
isLeftBottom = leftBottom;
isRightBottom = rightBottom;
}
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
return TransformationUtils.roundedCorners(pool, toTransform,
isLeftTop ? roundingRadius : 0,
isRightTop ? roundingRadius : 0,
isRightBottom ? roundingRadius : 0,
isLeftBottom ? roundingRadius : 0);
}
public static RoundRadiusTransform getDefault() {
if (mInstance == null) {
synchronized (RoundRadiusTransform.class) {
if (mInstance == null) {
mInstance = new RoundRadiusTransform(ScreenUtils.dp2px(MainApplication.getInstance(), 6));
mInstance.setNeedCorner(true, false, true, false);
}
}
}
return mInstance;
}
@Override
public boolean equals(Object o) {
if (o instanceof RoundRadiusTransform) {
RoundRadiusTransform other = (RoundRadiusTransform) o;
return roundingRadius == other.roundingRadius;
}
return false;
}
@Override
public int hashCode() {
return Util.hashCode(ID.hashCode(), Util.hashCode(roundingRadius));
}
@Override
public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
messageDigest.update(ID_BYTES);
byte[] radiusData = ByteBuffer.allocate(4).putInt(roundingRadius).array();
messageDigest.update(radiusData);
}
}
上面示例中默認設置的是左邊6dp的圓角右邊直角的顯示樣式。如果您看了RoundedCorners源碼,就會發現有很大的相似性,只是在transform方法返回時有區別。
所以有時候沒有必要重複發明輪子,有些輪子的零部件就在第三方提供的工具中,所需要的只是我們花點時間瞭解組拼下而已。