0

i'm using this code to have a circle imageview :

public class CircularImageView extends ImageView{
    private int borderWidth = 4;
    private int viewWidth;
    private int viewHeight;
    private Bitmap image;
    private Paint paint;
    private Paint paintBorder;
    private BitmapShader shader;

    public CircularImageView(Context context)
    {
        super(context);
        setup();
    }

    public CircularImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        setup();
    }

    public CircularImageView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        setup();
    }

    private void setup()
    {
        // init paint
        paint = new Paint();
        paint.setAntiAlias(true);

        paintBorder = new Paint();
        setBorderColor(Color.WHITE);
        paintBorder.setAntiAlias(true);
        this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
        paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
    }

    public void setBorderWidth(int borderWidth)
    {
        this.borderWidth = borderWidth;
        this.invalidate();
    }

    public void setBorderColor(int borderColor)
    {
        if (paintBorder != null)
            paintBorder.setColor(borderColor);

        this.invalidate();
    }

    private void loadBitmap()
    {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();

        if (bitmapDrawable != null)
            image = bitmapDrawable.getBitmap();
    }

    @SuppressLint("DrawAllocation")
    @Override
    public void onDraw(Canvas canvas)
    {
        // load the bitmap
        loadBitmap();

        // init shader
        if (image != null)
        {
            shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            paint.setShader(shader);
            int circleCenter = viewWidth / 2;

            // circleCenter is the x or y of the view's center
            // radius is the radius in pixels of the cirle to be drawn
            // paint contains the shader that will texture the shape
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - 4.0f, paintBorder);
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - 4.0f, paint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec, widthMeasureSpec);

        viewWidth = width - (borderWidth * 2);
        viewHeight = height - (borderWidth * 2);

        setMeasuredDimension(width, height);
    }

    private int measureWidth(int measureSpec)
    {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY)
        {
            // We were told how big to be
            result = specSize;
        }
        else
        {
            // Measure the text
            result = viewWidth;
        }

        return result;
    }

    private int measureHeight(int measureSpecHeight, int measureSpecWidth)
    {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpecHeight);
        int specSize = MeasureSpec.getSize(measureSpecHeight);

        if (specMode == MeasureSpec.EXACTLY)
        {
            // We were told how big to be
            result = specSize;
        }
        else
        {
// Measure the text (beware: ascent is a negative number)
result = viewHeight;
}
return (result + 2);
}
}

and in xml :

<com.milionbor.srp.adapter.CircularImageView
        android:id="@+id/img_goroh"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:src="@drawable/varzeshi" />

it's working perfect, also i use this code to show a image from the web :

public class DrawableManager {
   private final Map<String, Drawable> drawableMap;

   public DrawableManager() {
       drawableMap = new HashMap<String, Drawable>();
   }

   public Drawable fetchDrawable(String urlString) {
       if (drawableMap.containsKey(urlString)) {
           return drawableMap.get(urlString);
       }

       Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
       try {
           InputStream is = fetch(urlString);
           Drawable drawable = Drawable.createFromStream(is, "src");


           if (drawable != null) {
               drawableMap.put(urlString, drawable);
               Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", "
                       + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
                       + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
           } else {
             Log.w(this.getClass().getSimpleName(), "could not get thumbnail");
           }

           return drawable;
       } catch (MalformedURLException e) {
           Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
           return null;
       } catch (IOException e) {
           Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
           return null;
       }
   }

   public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
       if (drawableMap.containsKey(urlString)) {
           imageView.setImageDrawable(drawableMap.get(urlString));
       }

       final Handler handler = new Handler() {
           @SuppressWarnings("deprecation")
        @Override
           public void handleMessage(Message message) {
               // imageView.setImageDrawable((Drawable) message.obj);
               imageView.setBackgroundDrawable((Drawable) message.obj);
           }
       };

       Thread thread = new Thread() {
           @Override
           public void run() {
               //TODO : set imageView to a "pending" image
               Drawable drawable = fetchDrawable(urlString);
               Message message = handler.obtainMessage(1, drawable);
               handler.sendMessage(message);
           }
       };
       thread.start();
   }

   private InputStream fetch(String urlString) throws MalformedURLException, IOException {
       DefaultHttpClient httpClient = new DefaultHttpClient();
       HttpGet request = new HttpGet(urlString);
       HttpResponse response = httpClient.execute(request);
       return response.getEntity().getContent();
   }
}

and in my activity :

tasvir = my url...
ImageView iv = (ImageView) findViewById(R.id.imageView1);
DrawableManager dm = new DrawableManager();
dm.fetchDrawableOnThread(tasvir,iv);

it is working perfect too, but when i want to show the image that i get from the web in circle, it is not working (not showing in circle). so how can i fix it?

  • Where's the layout that contains `imageView1`? In the layout xml you've pasted, you have `img_goroh`. Is there a typo or are you showing the image on a different image view? – kha Apr 24 '15 at 14:37

2 Answers2

2

Use imageLoader

add this to your application:

public class YourApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        initImageLoader(getApplicationContext());
    }

    public static void initImageLoader(Context context) {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(null)
            .cacheInMemory(false)
            .cacheOnDisk(true)
            .considerExifParams(true)
            .displayer(new RoundedBitmapDisplayer(70))
            .build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .denyCacheImageMultipleSizesInMemory()
            .diskCacheFileNameGenerator(new Md5FileNameGenerator())
            .tasksProcessingOrder(QueueProcessingType.LIFO)
            .diskCacheSize(50 * 1024 * 1024)
            .tasksProcessingOrder(QueueProcessingType.LIFO)
            .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
            .memoryCacheSize(2 * 1024 * 1024)
            .defaultDisplayImageOptions(options)
            .build();
        ImageLoader.getInstance().init(config);
    }
}

Also compile this lib in your gradle settings

compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'

And then use like this:

ImageLoader.getInstance().displayImage(uri, imageView);

Hope that helps!

Ziem
  • 6,579
  • 8
  • 53
  • 86
Android Android
  • 724
  • 1
  • 7
  • 20
0

Here is my custom class

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;
        if (bmp.getWidth() != radius || bmp.getHeight() != radius)
            sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
        else
            sbmp = bmp;
        Bitmap output = Bitmap.createBitmap(sbmp.getWidth(),
                sbmp.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xffa19774;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(sbmp.getWidth() / 2 + 0.7f, sbmp.getHeight() / 2 + 0.7f,
                sbmp.getWidth() / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);


        return output;
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth(), h = getHeight();


        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }


}

And here is how I used that

public void loadBitmap(String url) {

        if (loadtarget == null) loadtarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                // do something with the Bitmap
                handleLoadedBitmap(bitmap);
            }

            @Override
            public void onBitmapFailed(Drawable drawable) {

            }

            @Override
            public void onPrepareLoad(Drawable drawable) {

            }


        };

        Picasso.with(activity).load(url).into(loadtarget);
    }

    public void handleLoadedBitmap(Bitmap b) {
        // do something here
        thumb_image.setImageBitmap(b);
        thumb_image.getLayoutParams().height = activity.getResources().getDrawable(R.drawable.editimage).getIntrinsicHeight();
        thumb_image.getLayoutParams().width = activity.getResources().getDrawable(R.drawable.editimage).getIntrinsicWidth();

    }

It works perfect for me.Hope it would help you also.Here you can check this Rounded ImageView

Community
  • 1
  • 1
Soham
  • 4,397
  • 11
  • 43
  • 71
  • Picasso is library for downloading images.Here is the link http://square.github.io/picasso/ . You can use Picasso,it's up to you. – Soham Apr 24 '15 at 14:56