Java 绘制矩形边框粗细
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4219511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw rectangle border thickness
提问by JPC
Is it possible to do draw a rectangle with a given border thickness in an easy way?
是否可以以简单的方式绘制具有给定边框厚度的矩形?
采纳答案by jjnguy
If you are drawing on a Graphics2Dobject, you can use the setStroke()
method:
如果您在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);
If this is being done on a Swing component and you are being passed a Graphics
object, you can downcast it to a Graphics2D
.
如果这是在 Swing 组件上完成的,并且您正在传递一个Graphics
对象,则可以将其向下转换为Graphics2D
.
Graphics2D g2 = (Graphics2D) g;
回答by Hatto
Here's how to do this : Border with colored line with thickness 5.
以下是如何做到这一点:用粗细为 5 的彩色线条边框。
Border linebor = BorderFactory.createLineBorder(new Color(0xAD85FF), 5);
回答by Mohit
**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);