在Java中添加边框
我试图创建一个图像,通过将像素从旧位置复制到新坐标,在Java上为现有图像添加边框。我的解决方案可行,但我想知道是否有更有效/更短的方法来实现这一点在Java中添加边框,java,Java,我试图创建一个图像,通过将像素从旧位置复制到新坐标,在Java上为现有图像添加边框。我的解决方案可行,但我想知道是否有更有效/更短的方法来实现这一点 /** Create a new image by adding a border to a specified image. * * @param p * @param borderWidth number of pixels in the border * @param borderColor color of the bor
/** Create a new image by adding a border to a specified image.
*
* @param p
* @param borderWidth number of pixels in the border
* @param borderColor color of the border.
* @return
*/
public static NewPic border(NewPic p, int borderWidth, Pixel borderColor) {
int w = p.getWidth() + (2 * borderWidth); // new width
int h = p.getHeight() + (2 * borderWidth); // new height
Pixel[][] src = p.getBitmap();
Pixel[][] tgt = new Pixel[w][h];
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
if (x < borderWidth || x >= (w - borderWidth) ||
y < borderWidth || y >= (h - borderWidth))
tgt[x][y] = borderColor;
else
tgt[x][y] = src[x - borderWidth][y - borderWidth];
}
}
return new NewPic(tgt);
}
/**通过向指定图像添加边框来创建新图像。
*
*@param p
*@param borderWidth边框中的像素数
*@param borderColor边框的颜色。
*@返回
*/
公共静态NewPic边框(NewPic p、整型边框宽度、像素边框颜色){
int w=p.getWidth()+(2*borderWidth);//新宽度
int h=p.getHeight()+(2*borderWidth);//新高度
像素[][]src=p.getBitmap();
像素[][]tgt=新像素[w][h];
对于(int x=0;x=(w-borderWidth)|
y=(h-borderWidth))
tgt[x][y]=边框颜色;
其他的
tgt[x][y]=src[x-边界宽度][y-边界宽度];
}
}
返回新的NewPic(tgt);
}
如果只是为了在屏幕上显示,而不是为了在图像上实际添加边框,而是为了在屏幕上显示带有边框的图像
将显示以黑色绘制的4像素(每条边上)边框
但是,如果真正的目的是重画图像,那么我将通过抓取每一行数组,然后使用ByteBuffer并通过批量put(…)
操作复制行数组(和边框元素),然后抓取整个ByteBuffer的内容作为数组填充回图像
这是否会对性能产生任何影响尚不清楚,在尝试优化之前和之后都要进行基准测试,因为最终生成的代码实际上可能会更慢
主要问题是,虽然系统数组函数允许批量复制和填充数组内容,但它没有提供一个实用程序来将其复制到目标数组的偏移量中;但是,NIO包中的缓冲区允许您非常轻松地执行此操作,因此,如果存在解决方案,则它位于NIO ByteBuffer或它的kin中
component.setBorder(BorderFactory.createMatteBorder(
4, 4, 4, 4, Color.BLACK));