2012-04-02 75 views
0

對於Andriod的我有這樣的代碼:繪製位圖,而不是矩形

public Tank(int color) { 
    bounds = new RectF(); 
    paint = new Paint(); 
    paint.setColor(color); 
} 

public void draw(Canvas canvas) { 
    bounds.set(x - radius, y - radius, x + radius, y + radius); 
    canvas.drawRect(bounds, paint); 
} 

我在哪裏畫一個矩形,但現在我要畫一個位圖,而不是一個矩形,但

bitTank = BitmapFactory.decodeRescource(getRescource(),R.drawable.ic_launcher); 

bitTank = BitmapFactory.decodeFile("C:\Users\...\res\drawable-hdpi\ic_launcher.png"); 

(兩者)結合

canvas.drawBitmap(bitTank, matrix, null); 

不起作用。第一個不知道getRescource(),第二個不再工作。我怎麼能意識到這一點? (代碼在坦克類中,另一個類調用繪圖函數)。

+0

感謝您的編輯,當我試圖格式化它時,它不工作... – user1053864 2012-04-02 13:31:46

回答

1

第二版本根本無法工作,因爲您正試圖從Android應用程序訪問PC上的文件。 Android不知道您的本地電腦。

使用第一個代碼,您需要一個Context的實例來訪問資源。您可以通過上下文到您的構造函數,然後使用它:

class Tank { 
    Context context; 
    ... 

    public Tank(int color, Context ctx) { 
     context = ctx; 

     bounds = new RectF(); 
     paint = new Paint(); 
     paint.setColor(color); 
    } 

    public void draw(Canvas canvas) { 
     ... 
     bitTank = BitmapFactory.decodeRescource(context.getRescources(),R.drawable.ic_launcher); 
     ... 
    } 
} 

雖然這不是達到你以後的唯一方法,它應該讓你開始。

+0

知道這讓我的問題看起來很愚蠢,謝謝:P – user1053864 2012-04-03 16:28:55

0

這是getResources()與's'的結尾。
此外,請確保您有一個上下文來獲取資源。如果您從Tank類中做了電話,你需要訪問上下文以另一種方式,無論是作爲YourActivity.this如果Tank是一個內部類的活動,或者在構造函數中,否則它傳遞:

public Tank(Context ctx, int color) { 
    bitmap = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.ic_launcher); 
    //... other loading 

}