Java Graphics2D - 仅在矩形上绘制角点

时间:2016-05-04 18:25:02

标签: java awt graphics2d

使用Java中的Graphics2D,如何使用Graphics2D对象中的drawLine功能创建一个只绘制其角(如下图所示)的矩形?

****                         ****
*                               *
*                               *

             CONTENT

*                               *
*                               *
****                         ****

1 个答案:

答案 0 :(得分:1)

我为此做了一个功能:

   public void drawCornerRectangle(Graphics2D g, int x, int y, int width, int height, int cornerLength) {
        //check width, height and cornerLength
        if ((width < 0) || (height < 0) || (cornerLength < 1)) {
            return;
        }
        //check if width or height is 0
        if(width == 0) {
            g.drawLine(x, y, x, y + cornerLength);
            g.drawLine(x, y + height, x, (y + height) - cornerLength);
            return;
        } else if (height == 0) {
            g.drawLine(x, y, x + cornerLength, y);
            g.drawLine(x + width, y, (x + width) - cornerLength, y);
            return;
        }
        //check cornerLength
        if(cornerLength > width/2 && cornerLength > height/2) {
            g.drawRect(x, y, width, height);
        } else {
            //left up corner
            g.drawLine(x, y, x + cornerLength, y);
            g.drawLine(x, y, x, y + cornerLength);

            //right up corner
            g.drawLine(x + width, y, (x + width) - cornerLength, y);
            g.drawLine(x + width, y, x + width, y + cornerLength);

            //left down corner
            g.drawLine(x, y + height, x + cornerLength, y + height);
            g.drawLine(x, y + height, x, (y + height) - cornerLength);

            //right down corner
            g.drawLine(x + width, y + height, (x + width) - cornerLength, y + height);
            g.drawLine(x + width, y + height, x + width, (y + height) - cornerLength);
        }
    } 

如何致电:

//for square:
drawCornerRectangle(g, 10, 10, 200, 200, 20); //the same width and height

//for rectangle    
drawCornerRectangle(g, 10, 10, 100, 150, 20);

希望这有帮助。