To display a jpg file, png etc. We have in the Canvas class a method called drawBitmap.

Issue:

Display the contents of a jpg file on the screen knowing it has a size of 250 pixels wide by 200 high.

1 – We created a project called: Proyecto042

We delete the TextView that automatically adds the Android Studio and define the ConstraintLayout id with the value: layout1:

 

Lesson 38 - Draw: an image in kotlin - Lesson 38 - Draw: an image in kotlin - Lesson 38 - Draw: an image in kotlin -

Download an image from the internet and resize it to 250 * 200 pixels. Copy this file to the res / mipmap-mdpi folder of our project.

 

Now we encode the class where the whole logic is:

package com.coding180.project042



import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.view.View

class MainActivity: AppCompatActivity () {
// coding180.com
    override fun onCreate (savedInstanceState: Bundle?) {
        super.onCreate (savedInstanceState)
        setContentView (R.layout.activity_main)

        val layout1 = findViewById (R.id.layout1) as android.support.constraint.ConstraintLayout
        val background = Canvass (this)
        layout1.addView (background)
    }

    internal inner class Canvass (context: Context): View (context) {

        override fun onDraw (canvas: Canvas) {
            canvas.drawRGB (0, 0, 255)
            val bmp = BitmapFactory.decodeResource (resources, R.mipmap.kotlinlogo)
            canvas.drawBitmap (bmp, 0f, 0f, null)
        }
    }
}

To recover the image of the file from the folder res / mipmap-mdpi we must use the decodeResource method:

            Val bmp = BitmapFactory.decodeResource (resources, R.mipmap.kotlinlogo)

Once we have created the object of the class Bitmap we proceed to position the image in the screen of the device:

            Canvas.drawBitmap (bmp, 0f, 0f, null)

The preview of the application is:

 

Lesson 38 - Draw: an image in kotlin - Lesson 38 - Draw: an image in kotlin - Lesson 38 - Draw: an image in kotlin -

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!