解决Glide4.0和圆角裁剪CenterCrop冲突

本文介绍使用Glide加载图片并实现圆角效果的两种方法:一是通过重写BitmapTransformation类,二是利用第三方库glide-transformations。这两种方法均可帮助开发者在Android应用中轻松实现图片的圆角显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两种方案:

1、重写BitmapTransformation

重写方法解决冲突,来自优快云的一个解决方案


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) {
        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);
        }

        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) {

    }
}

在加载的时候使用

RequestOptions myOptions = new RequestOptions()  
                .transform(new GlideRoundTransform(this,30));  

        Glide.with(this)  
                .load(R.drawable.item1)  
                .apply(myOptions)  
                .into(icon1);  

地址http://blog.youkuaiyun.com/flyinbed_/article/details/75506062

2、使用第三方框架

库地址:
https://github.com/wasabeef/glide-transformations

该库是专门针对glide的一个辅助类,包括裁剪
效果图
wapchief

引入方法

    compile 'jp.wasabeef:glide-transformations:3.0.1'

使用方法

   Glide.with(mContext)
                .load(aClass.img)
                .apply(RequestOptions.bitmapTransform(new MultiTransformation(
                        new CenterCrop(),
                        new RoundedCornersTransformation(SizeUtils.dp2px(5), 0, RoundedCornersTransformation.CornerType.TOP))))
                .into(imageView);

这里RoundedCornersTransformation的第一个参数需要转换成像素

### 使用 Glide 加载图片并裁剪圆角Android 开发中,使用 Glide 可以轻松实现加载网络图片的功能,并通过 `transform` 方法将其裁剪圆角图片。以下是完整的解决方案: #### 1. 添加依赖项 确保项目中的 `build.gradle` 文件已包含 Glide 的依赖项: ```gradle implementation 'com.github.bumptech.glide:glide:4.12.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0' ``` #### 2. 实现代码 以下是一个完整的代码示例,展示如何使用 Glide 将图片加载到 `ImageView` 并设置为圆角效果。 ```java import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; public class ImageLoader { public static void loadImageWithRoundedCorners(Context context, ImageView imageView, String imageUrl) { RequestOptions requestOptions = new RequestOptions(); requestOptions.transform(new CenterCrop(), new RoundedCorners(30)); // 设置圆角半径为30px Glide.with(context) .load(imageUrl) .apply(requestOptions) .into(imageView); } } ``` 此代码片段展示了如何利用 `RequestOptions` `transform` 方法来应用 `CenterCrop` 裁剪模式以及 `RoundedCorners` 圆角效果[^1]。 #### 3. RecyclerView 中的应用 如果是在 `RecyclerView` 的适配器中使用,则可以在 `onBindViewHolder` 方法中调用上述方法: ```java @Override public void onBindViewHolder(ViewHolder holder, int position) { String url = urls.get(position); ImageLoader.loadImageWithRoundedCorners( holder.itemView.getContext(), holder.imageView, url ); } ``` 这里需要注意的是,在 `RecyclerView` 中使用 Glide 时,它会自动处理 ViewHolder 的复用逻辑,因此无需手动管理生命周期或取消请求[^3]。 #### 4. 自定义封装工具类 为了提高可维护性重用性,可以创建一个通用的图片加载工具类,如下所示: ```java public class ImageLoadBaseTool { public static void display(Context context, ImageView imageView, String path, ImageConfig config, ImageLoadProcessInterface listener) { RequestBuilder<GlideDrawable> requestBuilder = Glide.with(context) .load(path) .placeholder(config.placeholderResId) .error(config.errorResId) .transform(new CenterCrop(), new RoundedCorners(config.cornerRadius)); if (listener != null) { requestBuilder.listener(new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { listener.onLoadFailed(); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { listener.onResourceReady(); return false; } }); } requestBuilder.into(imageView); } } // 配置类 public class ImageConfig { public final int placeholderResId; public final int errorResId; public final int cornerRadius; public ImageConfig(int placeholderResId, int errorResId, int cornerRadius) { this.placeholderResId = placeholderResId; this.errorResId = errorResId; this.cornerRadius = cornerRadius; } } ``` 以上代码实现了更灵活的图片加载功能,支持占位图、错误图以及回调接口[^2]。 --- ### 注意事项 - 如果需要更高的性能优化,建议启用缓存机制。 - 当前使用的 `RoundedCorners` 是基于像素单位的值,可以根据屏幕密度动态调整其大小。 - 在某些情况下可能需要禁用硬件加速以解决渲染问题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值