…
}
}
}
在requestCode
是REQUEST_CODE_ALBUM
的情况下:
doCrop(data?.data!!)
data?.data!!
即是选择图片返回的Uri
,可以直接使用,这里进行了下一步操作,剪裁
剪裁
private fun doCrop(sourceUri: Uri) {
Intrinsics.checkParameterIsNotNull(sourceUri, “资源为空”)
UCrop.of(sourceUri, getDestinationUri())//当前资源,保存目标位置
.withAspectRatio(1f, 1f)//宽高比
.withMaxResultSize(500, 500)//宽高
.start(this)
}
为了方便,这里使用了一个三方库UCrop,使用简单方便。
getDestinationUri()
是当前资源裁剪后保存的目标位置
private fun getDestinationUri(): Uri {
val fileName = String.format(“fr_crop_%s.jpg”, System.currentTimeMillis())
val cropFile = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName)
return Uri.fromFile(cropFile)
}
UCrop
的回调同样也在onActivityResult
中
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
when (requestCode) {
REQUEST_CODE_ALBUM -> {
doCrop(data?.data!!)
}
UCrop.REQUEST_CROP -> {
val resultUri: Uri = UCrop.getOutput(data!!)!!
val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(resultUri))
// todo
}
UCrop.RESULT_ERROR -> {
val error: Throwable = UCrop.getError(data!!)!!
ToastUtil.show(“图片剪裁失败” + error.message)
}
}
}
}
UCr