Glide是一個第三方套件,可用於載入圖片、影片、Gif等,也可利用網址來抓取網路圖片。
implementation ("com.github.bumptech.glide:glide:4.11.0") {
exclude group: "com.android.support"
}
implementation 'com.github.bumptech.glide:glide:4.13.2'
於AndroidManifest.xml添加網路權限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
String url = "{圖片網址}"
Glide.with(this).load(url).into(imageView);
這邊使用2022IT邦幫忙鐵人賽圖片,圖片出處:https://ithelp.ithome.com.tw/2022ironman/event
於drawable加入圖片:
建立RequestOptions物件,利用placeholder()方法拿取圖片,在Glide加入apply()方法:
RequestOptions requestOptions = new RequestOptions()
.placeholder(R.drawable.ic_baseline_cloud_download);
Glide.with(this)
.load(url)
.apply(requestOptions)
.into(imageView);
於drawable加入圖片:
於RequestOptions物件串接error() 方法:
RequestOptions requestOptions = new RequestOptions()
.placeholder(R.drawable.ic_baseline_cloud_download)
.error(R.drawable.ic_baseline_error_outline);
於RequestOptions物件串接override()方法:(欲使用原始尺寸添加參數Target.SIZE_ORIGINAL)
RequestOptions requestOptions = new RequestOptions()
.placeholder(R.drawable.ic_baseline_cloud_download)
.error(R.drawable.ic_baseline_error_outline)
.override(100, 100);
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
String url="{圖片位址}";
RequestOptions requestOptions = new RequestOptions()
.placeholder(R.drawable.ic_baseline_cloud_download)
.error(R.drawable.ic_baseline_error_outline)
.override(100, 100);
Glide.with(this)
.load(url)
.apply(requestOptions)
.into(imageView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="0dp"
android:layout_height="300dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_launcher_foreground" />
</androidx.constraintlayout.widget.ConstraintLayout>