2016-08-03 73 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'调用被一个接一个地绘制。 –