[学习]Glide的使用(一)

2021-02-22  本文已影响0人  吴敬悦

图片处理库 Glide

我就使用了很简单的方式,也就是官网给的示例:

Glide.with(context)
  .load(bitmaps[position])
  .into(holder.itemView as ImageView)

效果就很明显,在不使用的情况下,滑动的时候明显感觉卡,由于我使用的是本人的手机,用的图片是本人图库,所以就没有相关图了,如果有看到的,只需要操作一下看看就知道了。

1. 项目引入

打开项目下的 build.gradle ,在 buildscript>repositories 添加:

mavenCentral()
maven { url 'https://maven.google.com' }

打开 app 下的 build.gradle ,在 dependencies 中添加:

implementation 'com.github.bumptech.glide:glide:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.11.0'

在相同的文件下添加插件:

plugins {
  ...
  id 'kotlin-kapt'
  id 'kotlin-android-extensions'
}

2. 准备RecyclerView

2.1 Adapter

新建类 RecyclerViewHolder

class RecyclerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {}

新建视图对应 xml 文件,我取名为 image.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView 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:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/todo"
    tools:srcCompat="@tools:sample/avatars" />

新建类 MyRecyclerViewAdapter

class MyRecyclerViewAdapter(private val bitmaps: List<Bitmap>, val context: Context) :
    RecyclerView.Adapter<RecyclerViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
        return RecyclerViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.image, parent, false)
        )
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
        // 使用传统的方式
        //        (holder.itemView as ImageView).setImageBitmap(bitmaps[position])
        val para = holder.itemView.layoutParams
        val width = context.resources.displayMetrics.widthPixels / 2
        para.height = (bitmaps[position].height / bitmaps[position].width) * width
        para.width = width
        holder.itemView.layoutParams = para
        // 使用 glide 的方式
        Glide.with(context)
            .load(bitmaps[position])
            .into(holder.itemView as ImageView)
    }

    override fun getItemCount(): Int {
        return bitmaps.size
    }
}

2.2 建立联系

private fun success(images: List<Bitmap>) {
        val layout = GridLayoutManager(this, 2)
        lists.layoutManager = layout
        Log.e("吴敬悦", images.size.toString())
        lists.adapter = MyRecyclerViewAdapter(images, this)
}

3. 图片获取

获取相册里面的图片,我的测试手机是 android 10

private fun getAllPhotoInfo() {
        val lists = mutableListOf<Bitmap>()
        val mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val projImage = arrayOf(
            MediaStore.Images.Media._ID,
        )
        val mCursor = contentResolver.query(
            mImageUri,
            projImage,
            MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
            arrayOf("image/jpeg", "image/png"),
            MediaStore.Images.Media.DATE_MODIFIED + " desc"
        )
        // 限制数量,相册照片太多了
        var i = 0
        while (mCursor?.moveToNext() == true && i < MAX_COUNT) {
            try {
                val imageUri = ContentUris.withAppendedId(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media._ID))
                        .toLong()
                )
                Log.e("吴敬悦", imageUri.toString())
                val pfd = this.contentResolver.openFileDescriptor(imageUri, "r")
                lists.add(BitmapFactory.decodeFileDescriptor(pfd?.fileDescriptor))
            } catch (e: FileNotFoundException) {
                e.message?.let { Log.e("吴敬悦", it) }
            }
            i++
        }
        success(lists)
        mCursor?.close()
}

4. 权限处理

override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_READ_STORAGE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getAllPhotoInfo()
            } else {
                Toast.makeText(this, "Storage permission is required", Toast.LENGTH_LONG).show()
                requestStoragePermission()
            }
        }
}
private fun requestStoragePermission() {
        ActivityCompat.requestPermissions(
            this, arrayOf(permission.READ_EXTERNAL_STORAGE), REQUEST_READ_STORAGE
        )
}

5. 整个 MainActivity 代码

package com.example.glideapplication

import android.Manifest
import android.Manifest.permission
import android.app.Activity
import android.content.ContentUris
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import java.io.FileNotFoundException


class MainActivity : Activity() {
    private val REQUEST_READ_STORAGE: Int = 1
    private val MAX_COUNT = 50
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//版本判断
            if (checkSelfPermission(permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestStoragePermission()
            } else {
                getAllPhotoInfo()
            }
        }
    }

    private fun success(images: List<Bitmap>) {
        val layout = GridLayoutManager(this, 2)
        lists.layoutManager = layout
        Log.e("吴敬悦", images.size.toString())
        lists.adapter = MyRecyclerViewAdapter(images, this)
    }

    private fun requestStoragePermission() {
        ActivityCompat.requestPermissions(
            this, arrayOf(permission.READ_EXTERNAL_STORAGE), REQUEST_READ_STORAGE
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_READ_STORAGE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getAllPhotoInfo()
            } else {
                Toast.makeText(this, "Storage permission is required", Toast.LENGTH_LONG).show()
                requestStoragePermission()
            }
        }
    }

    /**
     * 读取手机中所有图片信息
     */
    private fun getAllPhotoInfo() {
        val lists = mutableListOf<Bitmap>()
        val mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val projImage = arrayOf(
            MediaStore.Images.Media._ID,
        )
        val mCursor = contentResolver.query(
            mImageUri,
            projImage,
            MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
            arrayOf("image/jpeg", "image/png"),
            MediaStore.Images.Media.DATE_MODIFIED + " desc"
        )
        // 限制数量,相册照片太多了
        var i = 0
        while (mCursor?.moveToNext() == true && i < MAX_COUNT) {
            try {
                val imageUri = ContentUris.withAppendedId(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media._ID))
                        .toLong()
                )
                Log.e("吴敬悦", imageUri.toString())
                val pfd = this.contentResolver.openFileDescriptor(imageUri, "r")
                lists.add(BitmapFactory.decodeFileDescriptor(pfd?.fileDescriptor))
            } catch (e: FileNotFoundException) {
                e.message?.let { Log.e("吴敬悦", it) }
            }
            i++
        }
        success(lists)
        mCursor?.close()
    }
}

6. 整个 activity_main.xml 文件

<?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">

  <androidx.recyclerview.widget.RecyclerView
      android:id="@+id/lists"
      android:layout_width="0dp"
      android:layout_height="0dp"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent">

  </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>
上一篇下一篇

猜你喜欢

热点阅读