我正在尝试仅在SWT中更新画布的一部分,但是我不知道该怎么做。

我读到我必须使用setClipping,文档确实说:
“将可以通过绘图操作更改的接收器区域设置为参数指定的矩形区域。为矩形指定null会将接收器的剪切区域恢复为其原始值。”

所以我只是尝试了一次,但是没有运气,这里有个简单的例子:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;


public class SimpleCanvas {

    boolean manualDraw=false;
    public void run() {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setText("Canvas Example");
        createContents(shell);
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }

    /**
     * Creates the main window's contents
     *
     * @param shell the main window
     */
    private void createContents(Shell shell) {
        shell.setLayout(new FillLayout());

        // Create a canvas
        Canvas canvas = new Canvas(shell, SWT.NONE);

        // Create a button on the canvas
        Button button = new Button(shell, SWT.PUSH);
        button.setBounds(10, 10, 300, 40);
        button.setText("TEST");
        button.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event e) {
                switch (e.type) {
                case SWT.Selection:
                    manualDraw=true;
                    canvas.redraw();
                    break;
                }
            }
        });

        // Create a paint handler for the canvas
        canvas.addPaintListener(new PaintListener() {
            public void paintControl(PaintEvent e) {

                if (manualDraw){
                    e.gc.setForeground(e.display.getSystemColor(SWT.COLOR_GREEN));
                    e.gc.setClipping(90,90,60,60);
                    e.gc.drawRectangle(90,90,30,30);
                    return ;
                }


                Rectangle rect = ((Canvas) e.widget).getBounds();
                e.gc.setForeground(e.display.getSystemColor(SWT.COLOR_RED));
                e.gc.drawText("DRAW TEXT", 0, 0);
                e.gc.dispose();
            }
        });
    }

    /**
     * The application entry point
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new SimpleCanvas().run();
    }
}


您能帮我了解我在做什么错吗?

先感谢您。

最佳答案

我发现了问题。为了只更新画布的一部分,我不必调用:

canvas.redraw();


并在其中绘制画布的一部分,但是从画布中获取GC并在其中使用setClipping,因此调用如下代码:

public void redrawCanvas (Canvas canvas) {
        GC gc = new GC(canvas);
        gc.setClipping(90,90,60,60);
        gc.drawRectangle(90,90,30,30);
        gc.dispose();
    }

10-06 09:04