Android kotlin 用户点击更换头像 拍照和相册选择
时间: 2023-11-24 21:45:15 浏览: 156
以下是一个 Android Kotlin 用户点击更换头像的示例代码,其中包括拍照和相册选择功能:
Step 1:在 build.gradle 文件中添加以下依赖项:
```kotlin
implementation 'com.github.bumptech.glide:glide:4.12.0'
implementation 'com.github.bumptech.glide:glide-kotlin:1.0.0'
implementation 'com.github.yalantis:ucrop:2.2.3-native'
```
Step 2:在 layout 文件中添加一个 ImageView 用于显示头像:
```xml
<ImageView
android:id="@+id/image_view_profile"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:src="@drawable/ic_profile_placeholder" />
```
Step 3:在 Activity 或 Fragment 中添加以下代码:
```kotlin
private lateinit var imageViewProfile: ImageView
private val REQUEST_IMAGE_CAPTURE = 1
private val REQUEST_IMAGE_PICK = 2
private var currentPhotoPath: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageViewProfile = findViewById(R.id.image_view_profile)
imageViewProfile.setOnClickListener {
showImagePickerDialog()
}
}
private fun showImagePickerDialog() {
val options = arrayOf<CharSequence>("拍照", "从相册选择", "取消")
val builder = AlertDialog.Builder(this)
builder.setTitle("选择图片")
builder.setItems(options) { dialog, item ->
when {
options[item] == "拍照" -> {
dispatchTakePictureIntent()
}
options[item] == "从相册选择" -> {
dispatchPickImageIntent()
}
options[item] == "取消" -> {
dialog.dismiss()
}
}
}
builder.show()
}
private fun dispatchTakePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(packageManager)?.also {
// Create the File where the photo should go
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
// Error occurred while creating the File
null
}
// Continue only if the File was successfully created
photoFile?.also {
val photoURI: Uri = FileProvider.getUriForFile(
this,
"${BuildConfig.APPLICATION_ID}.fileprovider",
it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
}
}
}
private fun createImageFile(): File? {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
private fun dispatchPickImageIntent() {
// Intent to pick image from gallery
val pickPhoto = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(pickPhoto, REQUEST_IMAGE_PICK)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_IMAGE_CAPTURE -> {
currentPhotoPath?.let {
cropImage(Uri.fromFile(File(it)))
}
}
REQUEST_IMAGE_PICK -> {
data?.data?.let {
cropImage(it)
}
}
UCrop.REQUEST_CROP -> {
val resultUri = UCrop.getOutput(data!!)
resultUri?.let {
Glide.with(this)
.load(it)
.into(imageViewProfile)
}
}
}
}
}
private fun cropImage(sourceUri: Uri) {
val destinationUri: Uri = Uri.fromFile(File(cacheDir, "${UUID.randomUUID()}.jpeg"))
val options = UCrop.Options()
options.setCompressionQuality(80)
UCrop.of(sourceUri, destinationUri)
.withAspectRatio(1f, 1f)
.withOptions(options)
.start(this)
}
```
以上代码实现了以下功能:
- 用户点击 ImageView 后弹出一个 AlertDialog,用户可以选择拍照、从相册选择或取消操作。
- 如果用户选择拍照,则启动相机应用,拍摄照片后返回结果。
- 如果用户选择从相册选择,则启动相册应用,用户选择一张照片后返回结果。
- 将返回的照片进行裁剪,并将结果显示在 ImageView 中。
这是一个基本的示例代码。根据您的需求,您可能需要进行一些修改。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)