You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Glide加载本地SVG文件至ImageView失败问题求助

解决Glide 4.16.0加载本地SVG文件失败的问题

核心原因

Glide核心库默认不支持SVG格式解码,直接加载会因缺少对应解码器失败;同时Glide无内置java.net.URI类型的ModelLoader,因此首次用URI加载触发NoModelLoaderAvailableException。

解决方案步骤

1. 添加Glide SVG扩展依赖

在Module级别的build.gradle中添加与核心Glide版本匹配的SVG处理扩展库:

implementation 'com.github.bumptech.glide:glide:4.16.0'
implementation 'com.github.bumptech.glide:svg:4.16.0'

2. 注册SVG解码器到Glide

创建自定义AppGlideModule类,注册SVG相关的加载器与解码器:

import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.load.resource.svg.SvgDecoder;
import com.bumptech.glide.load.resource.svg.SvgDrawableTranscoder;
import com.caverock.androidsvg.SVG;
import java.io.InputStream;

@GlideModule
public class MyAppGlideModule extends AppGlideModule {
    @Override
    public void registerComponents(Context context, Glide glide, Registry registry) {
        registry.append(InputStream.class, SVG.class, new SvgDecoder());
        registry.register(SVG.class, SvgDrawableTranscoder.class);
    }
}

注:添加@GlideModule注解后,Glide会自动生成对应API类,无需手动在Manifest中注册。

3. 修改加载代码

使用Glide的SVG加载能力加载本地文件:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    File imageFile = // 从公司集成模块获取的SVG文件实例
    ImageView imageView = findViewById(R.id.imageview);
    
    Glide.with(this)
            .as(SvgDrawable.class)
            .load(imageFile)
            .into(imageView);
}

权限说明

若SVG文件存储在应用内部目录(如getFilesDir()下),无需READ_EXTERNAL_STORAGE权限,可移除对应权限声明;若在外部存储,需确保已申请并获取该权限。


内容的提问来源于stack exchange,提问作者user1506104

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:06:07