I'm trying to draw some lines to cross a rectangle diagonally but the issue is that the lines get out of the rectangle boundaries, look at this image to understand what I mean:
here is the code used:
@Override
public void paint(Graphics gr) {
super.paint(gr);
gr.setColor(Color.blue);
int x = 100, y = 100, width = 100, height = 300;
gr.fillRect(x, y, width, height);
gr.setColor(Color.red);
// set stroke
Graphics2D g2d = (Graphics2D) gr;
g2d.setStroke(new BasicStroke(0.75f));
float unitHeight = 50f; // line space
int lines = (int) Math.ceil(height / unitHeight);
int lineOffset = width / 5;
for (int i = 1; i <= lines; ++i) {
g2d.drawLine(x + lineOffset, y, x, y + lineOffset);
g2d.drawLine(x + width - lineOffset, y + height, x + width, y + height - lineOffset);
int cellWidth = width / 3;
lineOffset += cellWidth;
}
}
I'm using Java Swing and AWT libraries to implement the solution, however I would use this for Android actually.
I tried some solutions but I counldn't manage to fully solve the problem, one of these tries was to check if the line starting point coordinates are exceeding the rectangle boundaries but couldn't set the point to the right position after that. I also tried to find the point where the line intersects with the rectangle boundary using straight line equation but still couldn't find the appropriate solution.
so basicly how to draw the lines inside the rectangle? also I don't have the option to draw over the lines outside the the rectangle to make them disappear, just in case someone thinks to do so.
Before the for
loop, you could add
g2d.setClip(x, y, width, height);
This makes any drawings you make outside of that boundary to be omitted and not be shown on the screen, which means that only the lines inside the rectangle will actually be printed out on the screen. When the for
loop has finished, you could then change the clip to the whole screen to allow for any other drawings that you may want to add.