我正在使用LibGDX创建Android游戏,任务是从图库插入个人资料照片?
在主活动中,我们编写以下代码从图库中获取图像:
class MainActivity : AppCompatActivity(), AndroidFragmentApplication.Callbacks {
private var blockImageFromGalleryResult: (Uri?) -> Unit = {}
private val selectImageFromGalleryResult = registerForActivityResult(ActivityResultContracts.GetContent()) {
uri: Uri? -> blockImageFromGalleryResult(uri)
}
fun selectImageFromGallery(block: (Uri?) -> Unit) {
blockImageFromGalleryResult = block
selectImageFromGalleryResult.launch("image/*")
}
在屏幕上纹理将在哪里,这是确定的,当你点击照片时,画廊将使用我们在主活动中编写的方法打开,这个方法将返回uri时选择一个图像,我们将这个yuri转换为一个位图和一个纹理:
class MenuScreen: AdvancedScreen(1280f, 727f) {
private val photoImage = Image(SpriteManager.MenuRegion.PHOTO.region)
private fun AdvancedStage.addPhoto() {
addActor(photoImage)
photoImage.apply {
setBounds(LM.photo)
toClickable().setOnClickListener {
MainActivity().selectImageFromGallery {
it?.let { uri ->
val bitmap: Bitmap = game.activity.contentResolver.openInputStream(uri).use { data -> BitmapFactory.decodeStream(data) }
runGDX {
val tex: Texture = Texture(bitmap.width, bitmap.height, Pixmap.Format.RGBA8888)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex.textureObjectHandle)
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0)
bitmap.recycle()
photoImage.drawable = TextureRegionDrawable(tex)
}
}
}
}
}
}