こんにちは。miyagawaです。
今回はGlideを使って角丸の画像を作成します。
まずはGlideライブラリをインポートします。
*2019年12月時点での最新版をインストールしています。
implementation 'com.github.bumptech.glide:glide:4.9.0'
ライブラリのインポートが完了したらGlideで画像を読み込む処理を付け加えます。
■URLから画像をそのまま読み込む
fun setImageFromUrl(context: Context, url: String, imageView: ImageView) { if (url.isEmpty()) return Glide.with(context) .asBitmap() .load(url) .into(imageView) }
■URLから画像を読み込み、円形に加工する
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から画像を読み込み、角丸をつける
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) } }) }
前節で紹介した機能以外にも細かく設定ができます。
■キャッシュから読み込む
val requestOptions: RequestOptions = RequestOptions() .diskCacheStrategy(DiskCacheStrategy.DATA)
■アニメーションなし
val requestOptions: RequestOptions = RequestOptions() .dontAnimate()
■CenterCrop
val requestOptions: RequestOptions = RequestOptions() .centerCrop()
■Placeholderを設定する
val requestOptions: RequestOptions = RequestOptions() .placeholder(R.drawable.image_placeholder)
Glideで画像の読み込みを行いました。
簡単に導入できるライブラリなので、今後も機会があれば使いたいと思います。