Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java Graphics 繪圖方法全解

Graphics 類提供了基本的繪圖能力,包括畫線段、矩形、圓形、橢圓、圓弧、多邊形與字符串,也能為圖形上色。

畫線段

public abstract void drawLine(int x1, int y1, int x2, int y2)

在目前坐標系中,以當前顏色從點 (x1, y1) 畫一條線到 (x2, y2)。x1、y1 是第一個點的橫縱坐標,x2、y2 是第二個點的橫縱坐標。

g.drawLine(10, 50, 100, 100);

畫矩形

public void drawRect(int x, int y, int width, int height)

繪製指定矩形的邊框。左右邊緣分別位於 x 與 x + width,上下邊緣分別位於 y 與 y + height,使用圖形上下文的當前顏色。x、y 為矩形左上角坐標,width 為寬度,height 為高度。

g.drawRect(120, 50, 200, 100);

畫橢圓

public abstract void drawOval(int x, int y, int width, int height)

繪製橢圓邊框。所得圓或橢圓剛好能放入由 x、y、width、height 指定的矩形中,覆蓋區域寬為 width + 1 像素、高為 height + 1 像素。x、y 是外接矩形左上角坐標。

g.drawOval(160, 160, 200, 100);

畫帶顏色的圖形

public abstract void setColor(Color c)

把當前顏色設為指定顏色,後續所有繪圖操作都會沿用。

g.setColor(Color.yellow);
g.fillRect(20, 70, 20, 30);   // 畫矩形著色塊

畫圓角矩形(近似的圓)

public abstract void drawRoundRect(int x, int y, int width, int height,
        int arcWidth, int arcHeight)

以當前顏色繪製圓角矩形邊框,邊緣位置規則同 drawRect。arcWidth 是四個角弧度的水平直徑,arcHeight 是垂直直徑;當兩者等於寬高時,視覺上就接近一個圓。

g.setColor(Color.red);
g.fillRoundRect(80, 100, 100, 100, 100, 100);   // 畫圓塊

畫圓弧

public abstract void drawArc(int x, int y, int width, int height,
        int startAngle, int arcAngle)

繪製覆蓋指定矩形的圓弧或橢圓弧邊框。弧從 startAngle 起跨越 arcAngle 度,使用當前顏色;0 度位於 3 點鐘方向,正值為逆時針、負值為順時針。弧的中心是該矩形的中心,覆蓋 width + 1 乘 height + 1 像素的區域。

角度是相對於外接矩形指定的,45 度恆落在橢圓中心到外接矩形右上角的連線上;因此若外接矩形某軸遠長於另一軸,弧的起訖點會沿長軸出現較明顯的偏斜。

g.drawArc(10, 40, 90, 50, 0, 180);    // 畫圓弧線
g.drawArc(100, 40, 90, 50, 180, 180); // 畫圓弧線
g.setColor(Color.yellow);
g.fillArc(10, 100, 40, 40, 0, -270);  // 填充缺右上角的四分之三橢圓
g.setColor(Color.green);
g.fillArc(60, 110, 110, 60, -90, -270); // 填充缺左下角的四分之三橢圓

畫多邊形

/** 繪制一個由 x 和 y 坐標數組定義的閉合多邊形,每對 (x, y) 坐標定義一個點 */
public abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints);

/** 填充由 x 和 y 坐標數組定義的閉合多邊形 */
public abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
int px[] = { 210, 220, 270, 250, 240 };
int py[] = { 220, 250, 300, 270, 220 };
g.drawPolygon(px, py, px.length);

畫字符串

public abstract void drawString(String str, int x, int y)

以當前字體與顏色繪製文字,最左側字符的基線位於 (x, y)。

g.setColor(Color.GREEN);
g.setFont(new Font("楷體", Font.BOLD, 20));
g.drawString("使用畫筆繪制的字符串內容", 220, 345);
Copyright © Linux教程網 All Rights Reserved