簡體   English   中英

Android中的applet getGraphics()等效於什么。 以及如何在onDraw()外部“繪制”

[英]What is the equivalent of the applet getGraphics() in Android. And how can I “draw” outside the onDraw()

我需要在Android中獲取圖形上下文,並且我已經讀到無法在onDraw()外部繪制,如何處理該問題,因為我需要圖形上下文在onDraw()外部繪制

我已經發布了我遇到問題的那部分代碼。

這是我遇到問題的小程序中David Eck教授的代碼。

synchronized void putSquare(int row, int col, int colorNum) {

         // draw one cell of the maze, to the graphics context "graphics"
        int w = totalWidth / columns;  // width of each cell
        int h = totalHeight / rows;    // height of each cell
        Graphics graphics = getGraphics();// This is the problem

            graphics.setColor(colorArray[colorNum]);
            graphics.fillRect( (col * w) + left, (row * h) + top, w, h );
}

我試圖將其轉換為Android

synchronized void putSquare(int row, int col, int colorNum, Canvas canvas) {
             try {
                 canvas = surfaceHolder.lockCanvas(null);// nullpointerexception

                   synchronized (surfaceHolder) {
                   Paint paint = new Paint():

                    // draw one cell of the maze, to the graphics context "graphics"
                   int w = totalWidth / columns;  // width of each cell
                   int h = totalHeight / rows;    // height of each cell
                   apaint.drawColor(color[colorNum]);
                    canvas.drawRect( (col * w) + left, (row * h) + top, w, h,  paint);
               }
             }


             finally {
                if (aCanvas != null) {
                    surfaceHolder.unlockCanvasAndPost(aCanvas);
                }
            }
}

putSquare()由makeMaze()調用

makeMaze() {
        maze = new int[rows][columns];  

        putSquare(rows, columns, colorNumber, mainCanvas);
}

makeMaze()在run()中調用,但在onDraw()不調用

public void run() {
    makeMaze()  
}

我得到了NullPointerException

onDraw()我調用了另一個方法。

 onDraw(Canvas conv) {
     //it also also putSquare()
    redrawMaze(conv)
 }

如果您不知道臟矩形的大小,請調用不帶參數的lockCanvas以鎖定整個繪圖區域,而不是傳遞null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM