Android - 在 Canvas 上淡出位图图像

标签 android image bitmap android-canvas fadeout

我正在 Canvas 上绘制缩放位图,并希望在指定时间淡出我的图像。

基本上,当我的角色图像越过 Canvas 的某个部分时,我要求角色图像慢慢消失(3 秒),然后页面自动重定向到下一个 java 类。

目前,我的图像只是重定向到新的 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);

然后在 Canvas 内绘制:

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
}

我在网上看过,但无法完全弄清楚如何让从我的游戏资源可绘制文件夹中获取的可绘制图像褪色。谢谢

最佳答案

如果您认为有可能需要更改淡入淡出动画,例如缩放和/或旋转,那么您应该使用动画 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
        }
    }
    ...
}

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

关于Android - 在 Canvas 上淡出位图图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18229088/

相关文章:

android - 在 Edittext android 的焦点上显示帮助消息

image - Windows Phone 8.1 裁剪图像

android - 在 Android 中访问 JPEG 图像的单独像素

Android ListView 的麻烦

android - 改造 Android : how to fetch Json data using id and display into textview

java - 互联网服务提供商定位器

python - 在 Python 中从现有的 Shopify 产品图片获取源 URL

image - 在 Matlab 中复制(绘制)一个图像到另一图像的区域内?

c# - 关于在 .NET 中保存位图的问题

iphone - LED显示屏字符集