假如你现在手里有的是xxx.svg文件或者说这个文件是https://xxx.com/xxx.svg,我们应该用什么方式去加载它呢?
Glide
implementation 'com.github.bumptech.glide:glide:4.15.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.15.1'
implementation 'com.caverock:androidsvg:1.2.1'
添加下面这几个类
/** Decodes an SVG internal representation from an {@link InputStream}. */
public class SvgDecoder implements ResourceDecoder<InputStream, SVG> {
@Override
public boolean handles(@NonNull InputStream source, @NonNull Options options) {
// TODO: Can we tell?
return true;
}
public Resource<SVG> decode(
@NonNull InputStream source, int width, int height, @NonNull Options options)
throws IOException {
try {
SVG svg = SVG.getFromInputStream(source);
if (width != SIZE_ORIGINAL) {
svg.setDocumentWidth(width);
}
if (height != SIZE_ORIGINAL) {
svg.setDocumentHeight(height);
}
return new SimpleResource<>(svg);
} catch (SVGParseException ex) {
throw new IOException("Cannot load SVG from stream", ex);
}
}
}
/**
* Convert the {@link SVG}'s internal representation to an Android-compatible one ({@link Picture}).
*/
public class SvgDrawableTranscoder implements ResourceTranscoder<SVG, PictureDrawable> {
@Nullable
@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);
}
}
/** Module for the SVG sample app. */
@GlideModule
public class SvgModule extends AppGlideModule {
@Override
public void registerComponents(
@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
registry
.register(SVG.class, PictureDrawable.class, new SvgDrawableTranscoder())
.append(InputStream.class, SVG.class, new SvgDecoder());
}
// Disable manifest parsing to avoid adding similar modules twice.
@Override
public boolean isManifestParsingEnabled() {
return false;
}
}
/**
* Listener which updates the {@link ImageView} to be software rendered, because {@link
* com.caverock.androidsvg.SVG SVG}/{@link android.graphics.Picture Picture} can't render on a
* hardware backed {@link android.graphics.Canvas Canvas}.
*/
public class SvgSoftwareLayerSetter implements RequestListener<PictureDrawable> {
@Override
public boolean onLoadFailed(
GlideException e, Object model, Target<PictureDrawable> target, boolean isFirstResource) {
ImageView view = ((ImageViewTarget<?>) target).getView();
view.setLayerType(ImageView.LAYER_TYPE_NONE, null);
return false;
}
@Override
public boolean onResourceReady(
PictureDrawable resource,
Object model,
Target<PictureDrawable> target,
DataSource dataSource,
boolean isFirstResource) {
ImageView view = ((ImageViewTarget<?>) target).getView();
view.setLayerType(ImageView.LAYER_TYPE_SOFTWARE, null);
return false;
}
}
结束
val uri: Uri = Uri.parse("https://www.xxx.com/xxx.svg")
Glide
.with(this)
.load(uri)
.into(findViewById(R.id.iv_svg))