Image size too small when loading SVG with Glide

2020-07-27 05:31发布

问题:

I'm using Glide to load images.

On my app I'm using the following sample to load a SVG image into my ImageView that is inside a 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);

The ImageView have a fixed width of 102dp and a fixed height of 94dp on the XML. But the images are getting smaller than they should after they are being loaded. Am I doing something wrong?

The scaleType is: android:scaleType="fitXY"

回答1:

I decided to open this question as an issue on the libs repository, and then I was able to fix the problem.

As it turned out, the problem was related to my SVG having a fixed size, so to fix it I had to modify my SvgDecoder.decode method, and add those three lines:

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

The method now looks like this:

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

Now it's working as it should.