我的Android之旅(十六)---如何从网上加载图片--Glide

    xiaoxiao2026-09-21  16

    Glide是google内部的一个用于图片加载开源框架,可以加载本地图片以及网络图片,默认图片的格式是RGB565,相比一般的RGB8888很大程度上降低内存的占用,Glide除了可以加载图片以外还可以加载动画,gif动画,和之前使用的ImageLoder相比Glide可以根据组件的生命周期来开启和结束加载图片,采用Drawable进行图片处理来防止出现OOM。

    使用Glide时,首先要在 build.gradle中导入该包:

    下面就是一个小的程序。来实现直接从网上获得图片:

    .xml文件中的代码

    package com.jerehedu.jereduch10; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; public class GideActivity extends AppCompatActivity { private ImageView image; private Button bt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gide); image= (ImageView) findViewById(R.id.image); bt= (Button) findViewById(R.id.bt); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Glide.with(GideActivity.this) .load("http://i04.pictn.sogoucdn.com/29222a740734a086") //从网上加载图片 .diskCacheStrategy(DiskCacheStrategy.ALL) //用于缓存 .error(R.mipmap.ic_launcher) //图片网址错误时默认显示的图片 .into(image); } }); } }

    写法比较简单,理解起来也比较容易,当然这个程序只是小小的应用了一下他的作用。在以后的软件开发中,用的非常多。

     程序中的各个方法的说明:

    with设置上下文,load加载链接之类的,error加载错误是显示的图片,placeholder加载中的默认图片,into将资源中的信息加载在img上。

    布局文件:

    <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.jerehedu.jereduch10.GideActivity"> <ImageView android:layout_width="match_parent" android:layout_height="300dp" android:id="@+id/image" android:scaleType="centerCrop" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/bt" android:text="加载" android:textSize="20sp" android:layout_below="@+id/image"/> </RelativeLayout>

    这种方法,不仅可以加载静态的图片,还可以加载动态图片,只需要更换图片的地址即可

    点击加载按钮,即可获得网络上的图片:

    由于要在网上获取图片,所以网络的好坏会影响图片加载的速度,所以要耐心等待

    

    转载请注明原文地址: https://ju.6miu.com/read-1312183.html
    最新回复(0)