2016-08-03 32 views
0

我做一個國際象棋的應用程序,當我繪製電路板的瓷磚,他們沒有得到在(透明)的背景顏色。基本上我想要什麼,它類似於在ImageView中會發生的情況,它會顯示帶有彩色背景的圖像(具有透明背景)。畫(從繪製)的位圖與彩色背景

這是代碼

private final Paint squareColor; 
private Rect tileRect; 
private Drawable pieceDrawable; 

public Tile(final int col, final int row) { 
    this.col = col; 
    this.row = row; 

    this.squareColor = new Paint(); 
    squareColor.setColor(isDark() ? Color.RED : Color.WHITE); 


} 

public void draw(final Canvas canvas) { 
    if(pieceDrawable != null) { 

     Bitmap image = ((BitmapDrawable) pieceDrawable).getBitmap(); 
     ColorFilter filter = new LightingColorFilter(squareColor.getColor(), Color.TRANSPARENT); 
     squareColor.setColorFilter(filter); 
     canvas.drawBitmap(image, null, tileRect, squareColor); 
    } else { 
     canvas.drawRect(tileRect, squareColor); 
    } 
} 

這是棋盤的樣子(左圖)

1 2

如果我drawBitmap call之前註釋掉這兩條線,我得到董事會作爲正確的形象。

ColorFilter filter = new LightingColorFilter(squareColor.getColor(), Color.TRANSPARENT); 
squareColor.setColorFilter(filter); 

我的作品是正常的圖像,透明背景的作品沒有在正方形中繪製。我怎麼能在的背後有紅色這塊? (就像它發生在具有背景顏色的相同圖像的ImageView或彩色視圖中一樣)

回答

1

如果pieceDrawable爲空,則只繪製背景。你的代碼更改爲:

public void draw(final Canvas canvas) { 
    canvas.drawRect(tileRect, squareColor); // Draws background no matter if place is empty. 
    if(pieceDrawable != null) { 
     Bitmap image = ((BitmapDrawable) pieceDrawable).getBitmap(); 
     ColorFilter filter = new LightingColorFilter(squareColor.getColor(), Color.TRANSPARENT); 
     squareColor.setColorFilter(filter); 
     canvas.drawBitmap(image, null, tileRect, squareColor); 
    } 
} 
+0

作品!非常感謝。你也知道我應該怎麼做,如果將來我想用可繪製/位圖替換瓷磚顏色? (如木圖像/掩模或此類) – BlackBox

+1

通過'drawBitmap()'一個只需更換'的drawRect()'呼叫。在'Canvas'上,'draw'調用被一個接一個地繪製。 –