绘制矩形边框厚度

发布于 2024-10-03 18:05:07 字数 31 浏览 2 评论 0原文

是否可以以简单的方式绘制具有给定边框厚度的矩形?

Is it possible to do draw a rectangle with a given border thickness in an easy way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

む无字情书 2024-10-10 18:05:07

如果您在 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;

If you are drawing on a Graphics2D object, you can use the setStroke() method:

Graphics2D g2;
double thickness = 2;
Stroke oldStroke = g2.getStroke();
g2.setStroke(new BasicStroke(thickness));
g2.drawRect(x, y, width, height);
g2.setStroke(oldStroke);

If this is being done on a Swing component and you are being passed a Graphics object, you can downcast it to a Graphics2D.

Graphics2D g2 = (Graphics2D) g;
贩梦商人 2024-10-10 18:05:07

操作方法如下:带有粗细为 5 的彩色线的边框。

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

Here's how to do this : Border with colored line with thickness 5.

Border linebor = BorderFactory.createLineBorder(new Color(0xAD85FF), 5);
蔚蓝源自深海 2024-10-10 18:05:07
**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);
**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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文