修订:问题是绘制一个四边边框,其中每一边都以纯色开始,然后在边框跨度内向内渐变为白色。挑战在于使边界的交叉点看起来无缝。为了实现这一点,可以绘制边界,然后使用三角形来“混合”角。如果绘制花边的矩形没有重叠,每个角可以使用两个三角形,或者如果两个平行边界边延伸边界的全长(即矩形重叠),每个角一个三角形就足够了(如下所示)。
private static final int GRADIENT_LENGTH = 29;
private static final int BAR_LENGTH = 25;
public static void paintGradientBorder(Graphics g, Color borderColor) {
Graphics2D g2 = (Graphics2D) g.create();
GradientPaint gradientColorWest = new GradientPaint(0, 0, borderColor,
GRADIENT_LENGTH, 0, Color.WHITE);
GradientPaint gradientColorEast = new GradientPaint(WINDOW_WIDTH - GRADIENT_LENGTH,
0, Color.WHITE, WINDOW_WIDTH, 0, borderColor);
GradientPaint gradientColorNorth= new GradientPaint(0, 0, borderColor, 0,
GRADIENT_LENGTH, Color.WHITE);
GradientPaint gradientColorSouth = new GradientPaint(0, WINDOW_HEIGHT - GRADIENT_LENGTH,
Color.WHITE,0, WINDOW_HEIGHT, borderColor);
//south bar
g2.setPaint(gradientColorSouth);
g2.fillRect(0, WINDOW_HEIGHT - BAR_LENGTH, WINDOW_WIDTH, BAR_LENGTH);
//north bar
g2.setPaint(gradientColorNorth);
g2.fillRect(0, 0, WINDOW_WIDTH, BAR_LENGTH);
//west bar
g2.setPaint(gradientColorWest);
g2.fillRect(0, BAR_LENGTH, BAR_LENGTH, WINDOW_HEIGHT - BAR_LENGTH * 2);
//east bar
g2.setPaint(gradientColorEast);
g2.fillRect(WINDOW_WIDTH - BAR_LENGTH, BAR_LENGTH, WINDOW_WIDTH, WINDOW_HEIGHT - BAR_LENGTH * 2);
//NORTH WEST CORNER
//left triangle
Polygon p = new Polygon();
p.addPoint(0, 0);
p.addPoint(BAR_LENGTH, BAR_LENGTH);
p.addPoint(0, BAR_LENGTH);
g2.setPaint(gradientColorWest);
g2.fillPolygon(p);
//NORTH EAST CORNER
//right triangle
p.reset();
p.addPoint(WINDOW_WIDTH, 0);
p.addPoint(WINDOW_WIDTH - BAR_LENGTH, BAR_LENGTH);
p.addPoint(WINDOW_WIDTH, BAR_LENGTH);
g2.setPaint(gradientColorEast);
g2.fillPolygon(p);
//SOUTH WEST CORNER
//left triangle
p.reset();
p.addPoint(0, WINDOW_HEIGHT);
p.addPoint(0,WINDOW_HEIGHT - BAR_LENGTH);
p.addPoint(BAR_LENGTH, WINDOW_HEIGHT - BAR_LENGTH);
g2.setPaint(gradientColorWest);
g2.fillPolygon(p);
//SOUTH EAST CORNER
//right triangle
p.reset();
p.addPoint(WINDOW_WIDTH, WINDOW_HEIGHT);
p.addPoint(WINDOW_WIDTH, WINDOW_HEIGHT - BAR_LENGTH);
p.addPoint(WINDOW_WIDTH - BAR_LENGTH, WINDOW_HEIGHT - BAR_LENGTH);
g2.setPaint(gradientColorEast);
g2.fillPolygon(p);
g2.dispose();
}
最佳答案
如果不与矩形相交而是使用多边形 (GeneralPath) 会怎样?
GeneralPath topBox = new GeneralPath();
topBox.moveTo(0, 0);
// upper right
topBox.lineTo(width, 0);
// lower right; move diagonally down and to the left as in a picture frame
topBox.lineTo(width - (insetX / 2), 0 + (insetY / 2));
// lower left
topBox.lineTo((insetX / 2), 0 + (insetY / 2));
topBox.closePath();
g2.fill(topBox);
这样矩形就不会重叠,而是在不同的部分之间会有很好的清晰边缘。