如何在圆形图像外插入边框?

时间:2015-11-14 14:03:28

标签: android

我想知道如何在圆形图像外插入灰色边框。

我使用此代码创建圆形图像视图:

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

我尝试使用以下行插入边框:

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

但它没有奏效,边界出现,但图像消失了。

1 个答案:

答案 0 :(得分:1)

这可以通过以下方式实现:

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