要畫上的任何控制(即繪製,擴展Drawable
),你需要創建一個實例GC
並使用它來繪製任何你需要的東西。不要忘記處理GC
實例。
我已經修改了Snippet10來說明如何做到這一點:
private static boolean mouseDown = false;
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Advanced Graphics");
FontData fd = shell.getFont().getFontData()[0];
final Font font = new Font(display, fd.getName(), 60, SWT.BOLD | SWT.ITALIC);
final Image image = new Image(display, 640, 480);
final Rectangle rect = image.getBounds();
GC gc = new GC(image);
gc.setBackground(display.getSystemColor(SWT.COLOR_RED));
gc.fillOval(rect.x, rect.y, rect.width, rect.height);
gc.dispose();
shell.addListener(SWT.Paint, new Listener() {
public void handleEvent(Event event) {
GC gc = event.gc;
Transform tr = new Transform(display);
tr.translate(50, 120);
tr.rotate(-30);
gc.drawImage(image, 0, 0, rect.width, rect.height, 0, 0, rect.width/2, rect.height/2);
gc.setAlpha(100);
gc.setTransform(tr);
Path path = new Path(display);
path.addString("SWT", 0, 0, font);
gc.setBackground(display.getSystemColor(SWT.COLOR_GREEN));
gc.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
gc.fillPath(path);
gc.drawPath(path);
tr.dispose();
path.dispose();
}
});
shell.addMouseListener(new MouseListener() {
@Override
public void mouseUp(MouseEvent e) {
mouseDown = false;
}
@Override
public void mouseDown(MouseEvent e) {
mouseDown = true;
}
@Override
public void mouseDoubleClick(MouseEvent e) {}
});
shell.addMouseMoveListener(new MouseMoveListener() {
@Override
public void mouseMove(MouseEvent e) {
if (!mouseDown)
return;
GC gc = new GC(shell);
gc.drawPoint(e.x, e.y);
gc.dispose();
}
});
shell.setSize(shell.computeSize(rect.width/2, rect.height/2));
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
image.dispose();
font.dispose();
display.dispose();
}
注意:每當Paint事件在控制燃煤,您的自定義圖紙會丟失。所以也許最好畫一幅圖像。然後調用控件上的重繪,該控件始終假定它必須繪製其背景,然後在背景上繪製該圖像。這樣,在每次重繪時,您都可以維護鼠標繪圖。
您不應該在paintEvents之外使用GC繪圖。您想在按下鼠標左鍵後在畫布上繪圖? – Kuba