はじめに
こんにちは。miyagawaです。
今回はGlideを使って角丸の画像を作成します。
使用するライブラリのインポート
まずはGlideライブラリをインポートします。
*2019年12月時点での最新版をインストールしています。
1 | implementation 'com.github.bumptech.glide:glide:4.9.0' |
Glideで画像を読み込む
ライブラリのインポートが完了したらGlideで画像を読み込む処理を付け加えます。
■URLから画像をそのまま読み込む
1 2 3 4 5 6 7 8 | fun setImageFromUrl(context: Context, url: String, imageView: ImageView) { if (url.isEmpty()) return Glide.with(context) .asBitmap() .load(url) .into(imageView) } |
■URLから画像を読み込み、円形に加工する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | fun setRoundImageFromUrl(context: Context, url: String, imageView: ImageView) { if (url.isEmpty()) return Glide.with(context) .asBitmap() .load(url) .into(object : BitmapImageViewTarget(imageView) { override fun setResource(resource: Bitmap?) { val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.resources, resource) circularBitmapDrawable.isCircular = true imageView.setImageDrawable(circularBitmapDrawable) } }) } |
■URLから画像を読み込み、角丸をつける
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | fun setCornerRadiusImageFromUrl(context: Context, url: String, imageView: ImageView) { if (url.isEmpty()) return val requestOptions = RequestOptions() .centerCrop() Glide.with(context) .asBitmap() .apply(requestOptions) .load(url) .into(object : BitmapImageViewTarget(imageView) { override fun setResource(resource: Bitmap?) { val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.resources, resource) circularBitmapDrawable.cornerRadius = 20.0f circularBitmapDrawable.setAntiAlias(true) imageView.setImageDrawable(circularBitmapDrawable) } }) } |
オプションまとめ
前節で紹介した機能以外にも細かく設定ができます。
■キャッシュから読み込む
1 2 | val requestOptions: RequestOptions = RequestOptions() .diskCacheStrategy(DiskCacheStrategy.DATA) |
■アニメーションなし
1 2 | val requestOptions: RequestOptions = RequestOptions() .dontAnimate() |
■CenterCrop
1 2 | val requestOptions: RequestOptions = RequestOptions() .centerCrop() |
■Placeholderを設定する
1 2 | val requestOptions: RequestOptions = RequestOptions() .placeholder(R.drawable.image_placeholder) |
さいごに
Glideで画像の読み込みを行いました。
簡単に導入できるライブラリなので、今後も機会があれば使いたいと思います。