android 使用Glide加载SVG时图像太小

k10s72fa  于 2022-11-20  发布在  Android
关注(0)|答案(2)|浏览(344)

我正在使用Glide加载图像。
在我的应用程序中,我使用以下示例将SVG图像加载到CardView中。

GenericRequestBuilder<Uri, InputStream, SVG, PictureDrawable> requestBuilder;

requestBuilder = Glide.with(mContext)
        .using(Glide.buildStreamModelLoader(Uri.class, mContext), InputStream.class)
        .from(Uri.class)
        .as(SVG.class)
        .transcode(new SvgDrawableTranscoder(), PictureDrawable.class)
        .sourceEncoder(new StreamEncoder())
        .cacheDecoder(new FileToStreamDecoder<>(new SVGDecoder()))
        .decoder(new SVGDecoder())
        .placeholder(R.drawable.modulo)
        .error(R.drawable.banner_error)
        .animate(android.R.anim.fade_in)
        .listener(new SvgSoftwareLayerSetter<Uri>());

requestBuilder
        .diskCacheStrategy(DiskCacheStrategy.NONE)
        .load(Uri.parse("http://foo.bar/blah"))
        .into(cardHolder.iv_card);

ImageView在XML中有固定的宽度102dp和固定的高度94dp。但是图像在加载后变得比它们应该的要小。我做错了什么吗?
scaleType为:android:scaleType="fitXY"

lhcgjxsq

lhcgjxsq1#

我决定以an issue on the libs repository的形式打开这个问题,然后我就可以修复这个问题了。
事实证明,这个问题与我的SVG具有固定大小有关,因此为了解决它,我必须修改我的SvgDecoder.decode方法,并添加以下三行:

svg.setDocumentWidth(width);
svg.setDocumentHeight(height);
svg.setDocumentPreserveAspectRatio(PreserveAspectRatio.STRETCH);

方法现在如下所示:

public Resource<SVG> decode(InputStream source, int width, int height) throws IOException {
    try {
        SVG svg = SVG.getFromInputStream(source);

        svg.setDocumentWidth(width);
        svg.setDocumentHeight(height);
        svg.setDocumentPreserveAspectRatio(PreserveAspectRatio.STRETCH);

        return new SimpleResource<>(svg);
    } catch (SVGParseException ex) {
        throw new IOException("Cannot load SVG from stream.", ex);
    }
}

现在它正常工作了。

ttvkxqim

ttvkxqim2#

除了已接受的答案-对我来说,解决方案不起作用,背后的原因是SVG中没有适当的视图框
正在添加

if (svg.documentViewBox == null)
svg.setDocumentViewBox(0f, 0f, svg.documentWidth, svg.documentHeight)

在更改SVG宽度/高度之前最后固定缩放

相关问题