2016-06-12 96 views
0

我試圖用Java圖形方法繪製一種十字準線。我寫了這個,但它似乎過度殺傷,我覺得它可以被簡化很多。我將包括它的樣子。更簡單的方法來繪製?

我該如何簡化?

graphics.setColor(mainColor); 
    graphics.drawRect(Mouse.getPos().x - 13, Mouse.getPos().y - 13, 27, 27); // Rectangle stroke. 
    graphics.drawRect(Mouse.getPos().x, Mouse.getPos().y - 512, 1, 500);  // Top y axis stroke. 
    graphics.drawRect(Mouse.getPos().x, Mouse.getPos().y + 13, 1, 500);  // Bottom y axis stroke. 
    graphics.drawRect(Mouse.getPos().x + 13, Mouse.getPos().y, 800, 1);  // Right x axis stroke. 
    graphics.drawRect(Mouse.getPos().x - 812, Mouse.getPos().y, 800, 1);  // left x axis stroke. 
    graphics.fillOval(Mouse.getPos().x - 3, Mouse.getPos().y - 3, 7, 7);  // Center dot stroke. 
    graphics.setColor(offColor); 
    graphics.drawRect(Mouse.getPos().x - 12, Mouse.getPos().y - 12, 25, 25); // Rectangle. 
    graphics.drawRect(Mouse.getPos().x, Mouse.getPos().y - 512, 0, 500);  // Top y axis line. 
    graphics.drawRect(Mouse.getPos().x, Mouse.getPos().y + 13, 0, 500);  // Bottom y axis line. 
    graphics.drawRect(Mouse.getPos().x + 13, Mouse.getPos().y, 800, 0);  // Right x axis line. 
    graphics.drawRect(Mouse.getPos().x - 812, Mouse.getPos().y, 800, 0);  // left x axis line. 
    graphics.fillOval(Mouse.getPos().x - 2, Mouse.getPos().y - 2, 5, 5);  // Center dot. 

這是它看起來像什麼,它應該是什麼樣子。 enter image description here

+6

你爲什麼不只是做一個PNG圖像並將其繪製在你想要的位置? – hexafraction

+0

首先,您可以將Mouse.getPos()。x指定給變量x,將Mouse.getPos()。y指定給變量y。這將使代碼更短,更易讀。 –

+0

有什麼具體的原因,你爲什麼使用'drawRect'而不是'drawLine'? –

回答

1

一個簡單的做法是製作一個包裝Graphics#drawRect方法的方法。

private static void drawRect (Graphics g, int x, int y, int width, int height) 
{ 
    g.drawRect(Mouse.getPos().x + x, Mouse.getPos().y + y, width, height); 
} 

那麼這個調用代碼都從

graphics.drawRect(Mouse.getPos().x - 13, Mouse.getPos().y - 13, 27, 27); // Rectangle stroke. 
graphics.drawRect(Mouse.getPos().x, Mouse.getPos().y - 512, 1, 500);  // Top y axis stroke. 
graphics.drawRect(Mouse.getPos().x, Mouse.getPos().y + 13, 1, 500);  // Bottom y axis stroke. 
graphics.drawRect(Mouse.getPos().x + 13, Mouse.getPos().y, 800, 1);  // Right x axis stroke. 
graphics.drawRect(Mouse.getPos().x - 812, Mouse.getPos().y, 800, 1);  // left x axis stroke. 

drawRect(graphics, -13, -13, 27, 27); // Rectangle stroke. 
drawRect(graphics, 0, -512, 1, 500); // Top y axis stroke. 
drawRect(graphics, 0, 13, 1, 500);  // Bottom y axis stroke. 
drawRect(graphics, 13, 0, 800, 1);  // Right x axis stroke. 
drawRect(graphics, -812, 0, 800, 1); // left x axis stroke. 
相關問題