Android - 在画布上淡出位图图像

Raj*_*ana 8 android image bitmap fadeout android-canvas

我正在绘制一个缩放的位图到画布上,并希望在指定的时间淡出我的图像.

基本上,当我的角色图像越过画布的某个部分时,我要求角色图像在页面自动重定向到下一个java类之前慢慢淡出(3秒).

目前,我的图像只是重定向到新的java类,请参阅下面的一些代码,了解我如何创建我的图像.

Resources res = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, res.getDisplayMetrics());
imgSpacing = (int) px / 2;
int size = (int) ((PhoneWidth / 5) - px);

chrImg = BitmapFactory.decodeResource(getResources(), R.drawable.character);
chrImg = Bitmap.createScaledBitmap(chrImg, size, size, true);
Run Code Online (Sandbox Code Playgroud)

然后在画布上绘制:

if(indexX == mazeFinishX && indexY == mazeFinishY)
{
    canvas.drawBitmap(finish, j * totalCellWidth, i * totalCellHeight, null);
    // As soon as the character moves over this square they are automatically re-directed to new page
    // This is where I want to fade the character image out before the re-direct
}
Run Code Online (Sandbox Code Playgroud)

我已经在网上看了,但是无法弄清楚如何让我的游戏资源可绘制文件夹中提取的可绘制图像的淡入效果.谢谢

Dan*_*ite 9

如果您认为有可能想要改变淡入淡出动画,例如缩放和/或旋转,那么您应该使用动画XML.

但是,对于快速位图淡入淡出,您可以重复发布延迟的失效消息.您可能希望将无效区域限制为字符位图的位置:

private static final int FADE_MILLISECONDS = 3000; // 3 second fade effect
private static final int FADE_STEP = 120;          // 120ms refresh

// Calculate our alpha step from our fade parameters
private static final int ALPHA_STEP = 255 / (FADE_MILLISECONDS / FADE_STEP);

// Initializes the alpha to 255
private Paint alphaPaint = new Paint();

// Need to keep track of the current alpha value
private int currentAlpha = 255;

@Override
protected void onDraw(Canvas canvas) {
    ...
    if(indexX == mazeFinishX && indexY == mazeFinishY) {

        // Drawing your wormhole?
        int x = j * totalCellWidth;
        int y = i * totalCellHeight;
        canvas.drawBitmap(finish, x, y, null);

        if (currentAlpha > 0) {

           // Draw your character at the current alpha value
           canvas.drawBitmap(chrImg, x, y, alphaPaint);

           // Update your alpha by a step
           alphaPaint.setAlpha(currentAlpha);
           currentAlpha -= ALPHA_STEP;

           // Assuming you hold on to the size from your createScaledBitmap call
           postInvalidateDelayed(FADE_STEP, x, y, x + size, y + size);

        } else {
           // No character draw, just reset your alpha paint
           currentAlpha = 255;
           alphaPaint.setAlpha(currentAlpha);

           // Now do your redirect
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我建议将常量FADE_MILLISECONDS和FADE_STEP放入res/integers.xml,这样它们就不会被硬编码.