Ad

Android - Draw Border Around ImageView

- 1 answer

I have defined an imageView and it I want to do two actions: Round its edges and draw a colored border around the bitmap. First I get it well, but the second one does not.

This is what I have done with canvas:

    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm, 150, 150, false);

    int min = Math.min(resizedBitmap.getWidth(), resizedBitmap.getHeight());

     Bitmap bitmapRounded = Bitmap.createBitmap(min, min, resizedBitmap.getConfig());

                Canvas canvas = new Canvas(bitmapRounded);
                Paint paint = new Paint();
                paint.setAntiAlias(true);
                paint.setShader(new BitmapShader(resizedBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                canvas.drawRoundRect((new RectF(0.0f, 0.0f, min, min)), min / 2, min / 2, paint);


    avatar.setImageBitmap(bitmapRounded);

    //I tried this, but don't work. 
    avatar.setPadding(1, 1, 1, 1);
    avatar.setBackgroundColor(getResources().getColor(R.color.negro));

Thanks you!

Ad

Answer

you can get rounded corner bitmap wirh border like below

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int color, int cornerDips, int borderDips, Context context) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int borderSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) borderDips,
                context.getResources().getDisplayMetrics());
        final int cornerSizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) cornerDips,
                context.getResources().getDisplayMetrics());
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        // prepare canvas for transfer
        paint.setAntiAlias(true);
        paint.setColor(0xFFFFFFFF);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectF, cornerSizePx, cornerSizePx, paint);

        // draw bitmap
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        // draw border
        paint.setColor(color);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth((float) borderSizePx);
        canvas.drawRoundRect(rectF, cornerSizePx, cornerSizePx, paint);

        return output;
    }
Ad
source: stackoverflow.com
Ad