在应用程序中,我使用以下示例将SVG图像加载到ImageView中:
Glide.with(context)
.using(Glide.buildStreamModelLoader(Uri.class, context), InputStream.class)
.from(Uri.class)
.as(SVG.class)
.transcode(new SvgDrawableTranscoder(), PictureDrawable.class)
.sourceEncoder(new StreamEncoder())
.cacheDecoder(new FileToStreamDecoder<>(new SvgDecoder()))
.decoder(new SvgDecoder())
.listener(new SvgSoftwareLayerSetter())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.load(uri)
.into(imageView);
xml中的ImageView如下所示:
<ImageView
android:layout_width="46dp"
android:layout_height="46dp"
android:layout_marginTop="25dp"
android:layout_gravity="center"
/>
因此,问题可以在下图中看到。右侧图标是从应用程序的资源设置的,而左侧图标是使用Glide从服务器加载的。由于某种原因,图像缩放不正确,看起来很模糊。
我已经尝试过这个答案的解决方案: Image size too small when loading SVG with Glide,但它不起作用。
答案 0 :(得分:3)
升级到滑行v4后,问题消失了。现在,我使用以下代码加载svg:
GlideApp.with(context)
.as(PictureDrawable.class)
.transition(withCrossFade())
.fitCenter()
.listener(new SvgSoftwareLayerSetter())
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.RESOURCE))
.load(uri).into(imageView);
在我的AppGlideModule中,我有:
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, Registry registry) {
registry.register(SVG.class, PictureDrawable.class, new SvgDrawableTranscoder())
.prepend(SVG.class, new SvgEncoder())
.append(InputStream.class, SVG.class, new SvgDecoder());
}
SvgDrawableTranscoder通过一种简单的方法将SVG转换为PictureDrawable:
public class SvgDrawableTranscoder implements ResourceTranscoder<SVG, PictureDrawable> {
@Override
public Resource<PictureDrawable> transcode(@NonNull Resource<SVG> toTranscode, @NonNull Options options) {
SVG svg = toTranscode.get();
Picture picture = svg.renderToPicture();
PictureDrawable drawable = new PictureDrawable(picture);
return new SimpleResource<>(drawable);
}
}
这就是我实现SvgEncoder类的方式:
public class SvgEncoder implements ResourceEncoder<SVG>{
@NonNull
@Override
public EncodeStrategy getEncodeStrategy(@NonNull Options options) {
return EncodeStrategy.SOURCE;
}
@Override
public boolean encode(@NonNull Resource<SVG> data, @NonNull File file, @NonNull Options options) {
try {
SVG svg = data.get();
Picture picture = svg.renderToPicture();
picture.writeToStream(new FileOutputStream(file));
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
答案 1 :(得分:0)
对于 Android VectorDrawable,令人惊讶的是以下对我有用(请参阅 this post):
Glide.with(context).load(myImage).dontTransform().into(myView);