【问题标题】:LibGDX (Android): How to select image from gallery and put into texture?LibGDX (Android): How to select image from gallery and put into texture?
【发布时间】:2022-12-28 04:29:38
【问题描述】:

I am creating a game for Android using LibGDX, the task is to insert a profile photo from the gallery?

【问题讨论】:

    标签: libgdx


    【解决方案1】:

    Kotlin SOLUTION 2022


    In the main activity we write the following code to get an image from the gallery:

    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/*")
    }
    

    On the screen where the texture will be, it is determined that when you click on the photo, the gallery will open using the method that we wrote in the main activity, this method will return the uri when choosing an image, we will convert this yuri to a bitmap and it to a texture:

    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)
                        }
                    }
                }
            }
        }
    }
    

    That's all, for more immersion in LibGDX for Android, you can read my article:

    https://medium.com/me/stats/post/4858e26734cf


    PS. Vel_daN: Love what You DO ?.


    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 2022-12-01
      • 1970-01-01
      • 2022-12-01
      相关资源
      最近更新 更多