是否可以轻松地绘制具有给定边框粗细的矩形?
答案 0 :(得分:36)
如果您正在使用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;
答案 1 :(得分:3)
以下是如何执行此操作:带有彩色线条的边框,厚度为5。
Border linebor = BorderFactory.createLineBorder(new Color(0xAD85FF), 5);
答案 2 :(得分: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);