打开相机
/**
* 打开相机
*/
private fun startCamera() {
val outFile = File(CAMERA_PATH)
try {
if (outFile.exists()) {
outFile.delete()
}
outFile.createNewFile()
} catch (e: Exception) {
Log.e("File", e.message)
}
val imgUri: Uri
imgUri = if (Build.VERSION.SDK_INT >= 24) {
FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", outFile)
} else {
Uri.fromFile(outFile)
}
//启动相机
val intent = Intent("android.media.action.IMAGE_CAPTURE")
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri)
startActivityForResult(intent, REQUEST_CODE_CAMERA)
}
打开相册
/**
* 打开相册
*/
private fun startAlbum() {
val intent = Intent(Intent.ACTION_PICK, null)
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
startActivityForResult(intent, REQUEST_CODE_ALBUM)
}
**使用 uCrop 裁剪
/**
* 图片裁剪
*/
private fun cropPhoto(uri: Uri) {
val cropFile = File(CROPED_PATH)
try {
if (cropFile.exists()) {
cropFile.delete()
}
cropFile.createNewFile()
} catch (e: Exception) {
Log.e("File", e.message)
}
val destination = Uri.fromFile(cropFile)
val option = UCrop.Options()
option.setCircleDimmedLayer(true)
option.setShowCropGrid(false)
option.setHideBottomControls(true)
option.setStatusBarColor(ContextCompat.getColor(this, R.color.color_cm))
option.setToolbarColor(ContextCompat.getColor(this, R.color.color_cm))
UCrop.of(uri, destination)
.withAspectRatio(1f, 1f)
.withOptions(option)
.start(this)
}
详情请参考