【问题标题】:Draw a bitmap (from a drawable) on a Canvas with a colored background在具有彩色背景的 Canvas 上绘制位图(来自可绘制对象)
【发布时间】:2016-08-03 21:43:21
【问题描述】:

我正在做一个国际象棋应用程序,当我绘制棋盘的图块时,它们不会在(透明)背景中着色。基本上我想要的,它类似于 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);
    }
}

这就是棋盘的样子(左图)

如果我在drawBitmap call 之前注释掉这两行,我会得到板作为正确的图像。

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

我的作品是具有透明背景的普通图像,其中没有在正方形中绘制作品。我怎样才能让这件作品后面出现红色? (就像在具有相同背景颜色的图像或彩色视图上的 ImageView 上一样)

【问题讨论】:

    标签: java android canvas bitmap background-color


    【解决方案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);
        }
    }
    

    【讨论】:

    • 有效!非常感谢。另外,如果将来我想用可绘制/位图替换平铺颜色,您知道该怎么办吗? (如木质图像/面具等)
    • 只需将drawRect() 调用替换为drawBitmap() 即可。在 Canvas 上,draw 调用被绘制在另一个之上。
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2013-08-28
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    相关资源
    最近更新 更多