簡體   English   中英

Glide 有加載 PNG 和 SVG 的方法嗎?

[英]Does Glide have a method for loading both PNG and SVG?

我正在使用Glide將一些圖像異步加載到我的一些ImageView ,我知道它可以處理PNGJPG等圖像,因為它可以處理SVG

事情是,據我所知,我加載這兩種圖像的方式不同。 喜歡:

加載“正常”圖像

Glide.with(mContext)
                .load("URL")
                .into(cardHolder.iv_card);

加載 SVG

GenericRequestBuilder<Uri, InputStream, SVG, PictureDrawable> 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())
        .listener(new SvgSoftwareLayerSetter<Uri>());

requestBuilder
        .diskCacheStrategy(DiskCacheStrategy.NONE)
        .load(Uri.parse("URL"))
        .into(cardHolder.iv_card);

如果我嘗試使用第一種方法加載 SVG,它將無法正常工作。 如果我嘗試用第二種方法加載 PNG 或 JPG,它也不起作用。

有沒有一種通用的方法來使用 Glide 加載兩種圖像類型?

我從中獲取這些圖像的服務器在我下載之前不會告訴我圖像類型。 它是一個 REST 服務器,資源將以"http://foo.bar/resource"類的方式檢索。 了解圖像類型的唯一方法是讀取 HEAD 響應。

您可以結合使用GlideAndroidSVG來實現您的目標。

有來自 Glide for SVG 的示例。 示例

設置請求生成器

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

使用帶有 uri 的 RequestBuilder

Uri uri = Uri.parse("http://upload.wikimedia.org/wikipedia/commons/e/e8/Svg_example3.svg");
requestBuilder
    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
    // SVG cannot be serialized so it's not worth to cache it
    .load(uri)
    .into(mImageView);

這樣你就可以實現你的目標。 我希望這是有幫助的。

我添加了一個靈活的解碼管道來解碼圖像或 SVG,也許可以提供幫助! 基於滑動 SVG 示例

解碼器

class SvgOrImageDecoder : ResourceDecoder<InputStream, SvgOrImageDecodedResource> {

override fun handles(source: InputStream, options: Options): Boolean {
    return true
}

@Throws(IOException::class)
override fun decode(
    source: InputStream, width: Int, height: Int,
    options: Options
): Resource<SvgOrImageDecodedResource>? {
    val array = source.readBytes()
    val svgInputStream = ByteArrayInputStream(array.clone())
    val pngInputStream = ByteArrayInputStream(array.clone())

    return try {
        val svg = SVG.getFromInputStream(svgInputStream)

        try {
            source.close()
            pngInputStream.close()
        } catch (e: IOException) {}

        SimpleResource(SvgOrImageDecodedResource(svg))
    } catch (ex: SVGParseException) {
        try {
            val bitmap = BitmapFactory.decodeStream(pngInputStream)
            SimpleResource(SvgOrImageDecodedResource(bitmap = bitmap))
        } catch (exception: Exception){
            try {
                source.close()
                pngInputStream.close()
            } catch (e: IOException) {}
            throw IOException("Cannot load SVG or Image from stream", ex)
        }
    }
}

轉碼器

class SvgOrImageDrawableTranscoder : ResourceTranscoder<SvgOrImageDecodedResource, PictureDrawable> {
override fun transcode(
    toTranscode: Resource<SvgOrImageDecodedResource>,
    options: Options
): Resource<PictureDrawable>? {
    val data = toTranscode.get()

    if (data.svg != null) {
        val picture = data.svg.renderToPicture()
        val drawable = PictureDrawable(picture)
        return SimpleResource(drawable)
    } else if (data.bitmap != null)
        return SimpleResource(PictureDrawable(renderToPicture(data.bitmap)))
    else return null
}

private fun renderToPicture(bitmap: Bitmap): Picture{
    val picture = Picture()
    val canvas = picture.beginRecording(bitmap.width, bitmap.height)
    canvas.drawBitmap(bitmap, null, RectF(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat()), null)
    picture.endRecording();

    return picture
}

解碼資源

data class SvgOrImageDecodedResource(
val svg:SVG? = null,
val bitmap: Bitmap? = null)

滑翔模塊

class AppGlideModule : AppGlideModule() {
override fun registerComponents(
    context: Context, glide: Glide, registry: Registry
) {
    registry.register(SvgOrImageDecodedResource::class.java, PictureDrawable::class.java, SvgOrImageDrawableTranscoder())
        .append(InputStream::class.java, SvgOrImageDecodedResource::class.java, SvgOrImageDecoder())
}

// Disable manifest parsing to avoid adding similar modules twice.
override fun isManifestParsingEnabled(): Boolean {
    return false
}

}

替代方式:kotlin + 線圈

此解決方案適用於 .svg 、 .png 、 .jpg

添加依賴:

//Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:1.2.0")
implementation("io.coil-kt:coil-svg:1.2.0")

將此函數添加到您的代碼中:

fun ImageView.loadUrl(url: String) {

val imageLoader = ImageLoader.Builder(this.context)
    .componentRegistry { add(SvgDecoder(this@loadSvg.context)) }
    .build()

val request = ImageRequest.Builder(this.context)
    .crossfade(true)
    .crossfade(500)
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.error)
    .data(url)
    .target(this)
    .build()

imageLoader.enqueue(request)
}

然后在您的活動或片段中調用此方法:

  imageView.loadUrl(url)
  // url example : https://upload.wikimedia.org/wikipedia/commons/3/36/Red_jungle_fowl_white_background.png

GlideToVectorYou沒有工作適合我,所以我用的線圈與線圈SVG擴展庫

對於其他人因為他們正在尋找一種在 Xamarin Android 中加載 SVG 的方法而到達此線程的其他人,接受的答案將不起作用,因為 Xamarin Glide nuget 包中似乎沒有很多這些類/方法。 這是對我有用的:

public static void SetSvgFromBytes (this ImageView imageView, byte[] bytes, int width, int height) {
            // Load the SVG from the bytes.
            var stream = new MemoryStream (bytes);
            var svg = SVG.GetFromInputStream (stream);
            // Create a Bitmap to render our SVG to.
            var bitmap = Bitmap.CreateBitmap (width, height, Bitmap.Config.Argb8888);
            // Create a Canvas to use for rendering.
            var canvas = new Canvas (bitmap);
            canvas.DrawRGB (255, 255, 255);
            // Now render the SVG to the Canvas.
            svg.RenderToCanvas (canvas);
            // Finally, populate the imageview from the Bitmap.
            imageView.SetImageBitmap (bitmap);
        }

它需要AndroidSVG.Xamarin nuget 包。

對於 Glide 4+,使用這個名為GlideToVectorYou 的庫,它在內部使用 Glide。

fun ImageView.loadSvg(url: String?) {
    GlideToVectorYou
        .init()
        .with(this.context)
        .setPlaceHolder(R.drawable.loading, R.drawable.actual)
        .load(Uri.parse(url), this)
}

來源: 如何使用畢加索庫加載遠程 svg 文件

我也遇到了同樣的問題,我所做的解決了我的問題,您只需 2 做 2 件工作完美的事情轉到鏈接https://github.com/corouteam/GlideToVectorYou 1- 只需復制過去的 maven 依賴項即可構建所有項目 {存儲庫 { ... maven { url 'https://jitpack.io' } } } 2-在應用程序構建中添加依賴項,如實現 'com.github.corouteam:GlideToVectorYou:v2.0.0'

謝謝它會決定加載 svg 確保你加載的和我正在做的一樣

Glide.with(holder.itemView.getContext()) .load(imageurl) .apply(new RequestOptions() .placeholder(R.drawable.placeholder) .dontAnimate() .fitCenter()) .into(holder.image);

如果有人仍然需要它,使用 Glide v4,您可以使用Glide-SVG庫輕松地向 Glide 添加 SVG 支持。 您也只需要導入Android SVG庫,並且您可以使用以下簡單、標准的代碼行使用 Glide 渲染任何 SVG:

GlideApp.with(this).load(url).into(imageView)

其中 GlideApp 是您本地生成的 Glide 模塊,如下所示:

@GlideModule
class GlideModule : AppGlideModule() {
    override fun isManifestParsingEnabled() = false

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        super.applyOptions(context, builder)
        builder.setLogLevel(Log.DEBUG)
    }
}

使用 Sharp 庫代替 Glide 庫

implementation 'com.pixplicity.sharp:library:1.1.0'

InputStream stream = response.body().byteStream();
                   Sharp.loadInputStream(stream).into(target);
                    stream.close();  

可以在這里看到一個例子https://www.geeksforgeeks.org/how-to-load-svg-from-url-in-android-imageview/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM