package com.zatackcoder.roundimage;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageLocal = findViewById(R.id.image_local);
        ImageView imageOnline = findViewById(R.id.image_online);
        //for local image resource
        Bitmap batmapBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.gull);
        RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), batmapBitmap);
        circularBitmapDrawable.setCircular(true);
        imageLocal.setImageDrawable(circularBitmapDrawable);
        //for online image resource
        new LoadAndShowImage(imageOnline).execute("https://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg");
    }

    class LoadAndShowImage extends AsyncTask<String, Void, RoundedBitmapDrawable> {
        ImageView imageView;

        public LoadAndShowImage(ImageView imageView) {
            this.imageView = imageView;
        }

        protected RoundedBitmapDrawable doInBackground(String... urls) {
            String imageURL = urls[0];
            RoundedBitmapDrawable roundedBitmapDrawable = null;
            try {
                InputStream in = new java.net.URL(imageURL).openStream();
                Bitmap bimage = BitmapFactory.decodeStream(in);
                roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bimage);
                roundedBitmapDrawable.setCircular(true);

            } catch (Exception e) {
                Log.e("LoadAndShowImage", e.getMessage());
            }
            return roundedBitmapDrawable;
        }

        protected void onPostExecute(RoundedBitmapDrawable result) {
            imageView.setImageDrawable(result);
        }
    }
}
