[英]Image becomes blurry when loading SVG with Glide
在應用程序中,我使用以下示例將 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 ,但它不起作用。
升級到 glide 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;
}
}
}
對於 Android VectorDrawable s,令人驚訝的是以下對我有用(參見這篇文章):
Glide.with(context).load(myImage).dontTransform().into(myView);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.