绘制矩形边框厚度

30

有没有一种简单的方法来绘制一个给定边框厚度的矩形呢?

3个回答

50

如果你正在 Graphics2D 对象上进行绘制,你可以使用 setStroke() 方法:

Graphics2D g2;
double thickness = 2;
Stroke oldStroke = g2.getStroke();
g2.setStroke(new BasicStroke(thickness));
g2.drawRect(x, y, width, height);
g2.setStroke(oldStroke);
如果这是在Swing组件上进行的,并且您被传递了一个Graphics对象,您可以将其向下转换为Graphics2D
Graphics2D g2 = (Graphics2D) g;

2
我需要取消描边吗? - JPC
1
@JPC,是的。笔画将保持较粗的状态。我会添加代码来解决这个问题。请稍等。 - jjnguy

1

以下是如何做到这一点:使用厚度为5的有色线框绕边。

Border linebor = BorderFactory.createLineBorder(new Color(0xAD85FF), 5);

3
未回答问题。 - Moritz Schmidt

0
**Tested code with buffered image with different thickness values**:

Graphics2D g = bufferedImage.createGraphics();

int height = //image height

int width = //image height

int borderWidth = //border thickness

int borderControl = 1;

//set border color

g.setColor(Color.BLACK);

//set border thickness

g.setStroke(new BasicStroke(borderWidth));

//to fix issue for even numbers

if(borderWidth%2 == 0){

borderControl = 0;

}

g.drawLine(0, 0, 0, height);

g.drawLine(0, 0, width, 0);

g.drawLine(0, height – borderControl, width, height – borderControl);

g.drawLine(width – borderControl, height – borderControl, width – borderControl, 0);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接