Thursday, March 8, 2018

android kotlin - ImageView set image programmatically

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*
import android.graphics.BitmapFactory
import java.io.IOException
import android.os.AsyncTask
import android.widget.ImageView
import android.widget.Toast
import java.net.URL


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Create a new bitmap and display it on image view
        image_view_bitmap.setImageBitmap(
                drawCircle(Color.RED,Color.YELLOW,700,400)
        )


        // Display an image on image view from drawable
        image_view_drawable.setImageDrawable(
                ContextCompat.getDrawable(
                        applicationContext, // Context
                        R.drawable.gradient_rectangle // Drawable
                )
        )


        // Display an image on image view from resource
        image_view_resource.setImageResource(R.drawable.flower)


        // Display an image into image view from assets folder
        val assetsBitmap:Bitmap? = getBitmapFromAssets("flower8.jpg")
        image_view_assets.setImageBitmap(assetsBitmap)


        // Display an image to image view from url
        DownLoadImageTask(image_view_url)
                .execute("https://www.gstatic.com/android/market_images/web/play_prism_hlock_2x.png")

    }



    // Custom method to get assets folder image as bitmap
    private fun getBitmapFromAssets(fileName: String): Bitmap? {
        return try {
            BitmapFactory.decodeStream(assets.open(fileName))
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }



    // Method to draw a circle on a canvas and generate bitmap
    private fun drawCircle(bgColor:Int=Color.TRANSPARENT,
                           circleColor:Int= Color.WHITE, width:Int=200, height:Int=200): Bitmap {
        // Initialize a new Bitmap object
        val bitmap: Bitmap = Bitmap.createBitmap(
                width, // Width
                height, // Height
                Bitmap.Config.ARGB_8888 // Config
        )

        // Initialize a new Canvas instance
        val canvas: Canvas = Canvas(bitmap)

        // Draw a solid color to the canvas background
        canvas.drawColor(bgColor)

        // Initialize a new Paint instance to draw the Circle
        val paint: Paint = Paint()
        paint.style = Paint.Style.FILL
        paint.color = circleColor
        paint.isAntiAlias = true

        // Calculate the available radius of canvas
        val radius:Int = Math.min(canvas.width,canvas.height/2)

        // Set a pixels value to padding around the circle
        val padding:Int = 5

        // Finally, draw the circle on the canvas
        canvas.drawCircle(
                (canvas.width / 2).toFloat(), // cx
                (canvas.height / 2).toFloat(), // cy
                (radius - padding).toFloat(), // Radius
                paint // Paint
        )

        // Return the newly created bitmap
        return bitmap
    }
}



// Class to download an image from url and display it into an image view
private class DownLoadImageTask(internal val imageView: ImageView) : AsyncTask<String, Void, Bitmap?>() {
    override fun doInBackground(vararg urls: String): Bitmap? {
        val urlOfImage = urls[0]
        return try {
            val inputStream = URL(urlOfImage).openStream()
            BitmapFactory.decodeStream(inputStream)
        } catch (e: Exception) { // Catch the download exception
            e.printStackTrace()
            null
        }
    }
    override fun onPostExecute(result: Bitmap?) {
        if(result!=null){
            // Display the downloaded image into image view
            Toast.makeText(imageView.context,"download success",Toast.LENGTH_SHORT).show()
            imageView.setImageBitmap(result)
        }else{
            Toast.makeText(imageView.context,"Error downloading",Toast.LENGTH_SHORT).show()
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#deeadc"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp"
        >
        <ImageView
            android:id="@+id/image_view_bitmap"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            />
        <ImageView
            android:id="@+id/image_view_drawable"
            android:layout_width="300dp"
            android:layout_height="100dp"
            android:layout_margin="20dp"
            />
        <ImageView
            android:id="@+id/image_view_resource"
            android:layout_width="300dp"
            android:layout_height="200dp"
            android:layout_margin="20dp"
            />
        <ImageView
            android:id="@+id/image_view_assets"
            android:layout_width="300dp"
            android:layout_height="200dp"
            android:layout_margin="20dp"
            />
        <ImageView
            android:id="@+id/image_view_url"
            android:layout_width="300dp"
            android:layout_height="200dp"
            android:layout_margin="20dp"
            />
    </LinearLayout>
</ScrollView>
res/drawable/gradient_rectangle.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:startColor="#ff6d6d"
                android:centerColor="#69d14d"
                android:endColor="#ffe02e"
                android:angle="45"
                />
            <corners android:radius="10dp"/>
        </shape>
    </item>
</selector>