Michael Jackson
Michael Jackson

Reputation: 376

How can I insert a border outside my circular image?

I would like to know how can I insert a grey border outside an circular image.

I'm using this code to create circular imageviews:

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;
    }

I tried to insert the border using these lines:

paint.setStrokeWidth(4);
paint.setStyle(Style.STROKE);

But it didn't worked, the border appeared, but the image disappeared.

Upvotes: 2

Views: 292

Answers (1)

Androider
Androider

Reputation: 3873

This can be achieved as follows:

   //put your bitmap here 
             Bitmap mIcon11=    MainActivity.drawableToBitmap(getResources().getDrawable(R.drawable.crow)); 

              Bitmap output = Bitmap.createBitmap(mIcon11.getWidth(),
                        mIcon11.getHeight(), Config.ARGB_8888);
                Canvas canvas = new Canvas(output);

                final Rect itemRect = new Rect(0, 0, mIcon11.getWidth(), mIcon11.getHeight());


             RectF roundRect = new RectF(itemRect);
             Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  //your bitmap here  
             Bitmap bitmap = MainActivity.drawableToBitmap(getResources().getDrawable(R.drawable.crow));

             mPaint.setStyle(Paint.Style.FILL);
             mPaint.setColor(Color.WHITE);
             canvas.drawRoundRect(roundRect, 100, 100, mPaint);

             roundRect.set(itemRect.left + 5, itemRect.top + 5, itemRect.right - 5, itemRect.bottom - 5);
             Path clipPath = new Path();
            //roundness of border
             clipPath.addRoundRect(roundRect, 100, 100, Path.Direction.CW);
             canvas.save(Canvas.CLIP_SAVE_FLAG);
             canvas.clipPath(clipPath);
             canvas.drawBitmap(bitmap, null, roundRect, mPaint);
             canvas.restore();
             myImageView.setImageBitmap(output);

Upvotes: 1

Related Questions