Android-在ImageView周围绘制边框

时间:2019-04-29 11:28:57

标签: android canvas imageview

我已经定义了imageView,它想做两个动作:使其边缘变圆并在位图周围绘制彩色边框。首先,我感觉很好,但是第二个却没有。

这是我对画布所做的:

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

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以获得如下所示的圆角位图和边框

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