简体   繁体   English

Java Graphics2D - 仅在矩形上绘制角

[英]Java Graphics2D - drawing corners only on a rectangle

With Graphics2D in Java, How would you create a rectangle that only has its corners drawn (as illustrated below) using the drawLine feature within the Graphics2D object?使用 Java 中的 Graphics2D,您将如何使用 Graphics2D 对象中的 drawLine 功能创建一个仅绘制角的矩形(如下图所示)?

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

             CONTENT

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

I have made a function for this:我为此做了一个功能:

   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);
        }
    } 

how to call:如何调用:

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

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

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM