How to set a circular image on ImageView, coming from the server.
How to set an image on ImageView in android?
174222-Aug-2018
Updated on 02-Jul-2023
Home / DeveloperSection / Forums / How to set an image on ImageView in android?
How to set a circular image on ImageView, coming from the server.
Aryan Kumar
02-Jul-2023Sure, here is how to set an image on image view in Android:
Code snippet
This code will first get the image view by calling the
findViewById()
method. Then, it will set the image in the image view by calling thesetImageBitmap()
method of the image view.The
setImageBitmap()
method has one parameter:The bitmap can be obtained from a variety of sources, such as:
To use this code, you would need to call the
setImage()
method in your app. For example, you could call the method in your app'sonCreate()
method.Here is an example of how you could call the
setImage()
method in your app'sonCreate()
method:Code snippet
When you run the app, you will see an image view with the image that you loaded from the file.
Arti Mishra
22-Aug-2018/* Create an object of ImageView */
ImageView myImage= (ImageView) findViewById(R.id.edit_image);
/* Picasso is a powerful image downloading and caching library.*/
Picasso.with(getApplicationContext())
.load("https://www.mysite.com//Contents/images/User%20Image/"+SaveSharedPreference.getPrefUserId(this) + ".png")
.transform(new CircleTransformation())
.into(myImage);
CircleTransformation.java
package com.example.msclient010.mindstickqna.Utils;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.squareup.picasso.Transformation;
/**
* Created by msclient010 on 2/2/2018.
*/
public class CircleTransformation implements Transformation {
@Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
@Override
public String key() {
return "circle";
}
}