如何在位图周围创建白色边框?

eri*_*lee 16 android bitmap

例如,我希望在位图的所有4侧围绕10像素的白色边框.我没有将它用于imageview我目前正在使用此代码来裁剪图像.我可以知道如何在其中添加白色边框吗?

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();

    // Compute the scaling factors to fit the new height and width, respectively.
    // To cover the final image, the final scaling will be the bigger 
    // of these two.
    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    // Now get the size of the source bitmap when scaled
    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    // Let's find out the upper left coordinates if the scaled bitmap
    // should be centered in the new size give by the parameters
    float left = (newWidth - scaledWidth) / 2;
    float top = (newHeight - scaledHeight) / 2;

    // The target rectangle for the new, scaled version of the source bitmap will now
    // be
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

    // Finally, we create a new bitmap of the specified size and draw our new,
    // scaled bitmap onto it.
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
    Canvas canvas = new Canvas(dest);
    canvas.drawBitmap(source, null, targetRect, null);

    return dest;
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*lle 65

我为此写了一个函数:

private Bitmap addWhiteBorder(Bitmap bmp, int borderSize) {
    Bitmap bmpWithBorder = Bitmap.createBitmap(bmp.getWidth() + borderSize * 2, bmp.getHeight() + borderSize * 2, bmp.getConfig());
    Canvas canvas = new Canvas(bmpWithBorder);
    canvas.drawColor(Color.WHITE);
    canvas.drawBitmap(bmp, borderSize, borderSize, null);
    return bmpWithBorder;
}
Run Code Online (Sandbox Code Playgroud)

基本上它创建了一个新的Bitmap,为每个维度添加2*bordersize,然后在其上绘制原始Bitmap,用borderize抵消它.

  • 这在图像视图大小高于显示的图像大小时起作用,并且具有背景和填充的边界的常规方法失败,因为某些部分过度填充其他部分.这种方法很完美.荣誉. (2认同)
  • 完美的代码。borderSize需要浮点数才能在drawBitmap()方法中使用 (2认同)

cag*_*187 13

至于这样做的方式.您使位图大于添加到它的位图,然后用您想要的背景填充画布.如果您需要添加其他效果,可以查看画布选项以剪裁矩形并添加圆角等.

RectF targetRect = new RectF(left+10, top+10, left + scaledWidth, top + scaledHeight);
Bitmap dest = Bitmap.createBitmap(newWidth+20, newHeight+20, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(source, null, targetRect, null);
Run Code Online (Sandbox Code Playgroud)

  • 你有基本的想法玩targetRect和位图大小,以获得你想要的效果. (4认同)