You need to enable JavaScript to run this app. Android实现图片翻转与滤镜功能时翻转后滤镜消失问题求解
优惠活动
大模型
产品
解决方案
定价
更多

Android实现图片翻转与滤镜功能时翻转后滤镜消失问题求解

问题根因
  • 你当前的翻转、滤镜操作都基于初始的scaledBitmap(未做任何修改的原始缩放图)执行,每次操作都不会保留上一步的修改结果,因此后执行的翻转操作会直接覆盖之前的滤镜效果
  • 现有fliph方法本身存在语法错误:方法缺少闭合大括号,且返回的是未定义的变量bit,实际创建的变量名为bit1
修复方案

新增全局变量currentBitmap存储当前已应用所有修改的图片实例,所有操作都基于currentBitmap执行,操作完成后将新结果回写给currentBitmap再渲染到控件,即可保留叠加效果。

修正后代码
// 新增全局变量,初始化时赋值为scaledBitmap
private Bitmap currentBitmap;

// 页面初始化阶段添加这行赋值
currentBitmap = scaledBitmap;

public void Flipimg(View v1){
    currentBitmap = fliph(currentBitmap);
    img1.setImageBitmap(currentBitmap);
}

public Bitmap fliph(Bitmap bms){
    Matrix mat = new Matrix();
    mat.setScale(-1, 1);
    Bitmap bit1=Bitmap.createBitmap( bms, 0, 0, bms.getWidth(), bms.getHeight(), mat, true);
    return bit1;
}

public void Filterimg(View v2){
    currentBitmap = applyGreyscaleEffect(currentBitmap);
    img1.setImageBitmap(currentBitmap);
}

public Bitmap applyGreyscaleEffect(Bitmap src) {
    final double GS_RED = 0.299;
    final double GS_GREEN = 0.587;
    final double GS_BLUE = 0.114;
    Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
    int A, R, G, B;
    int pixel;
    int width = src.getWidth();
    int height = src.getHeight();
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            pixel = src.getPixel(x, y);
            A = Color.alpha(pixel);
            R = Color.red(pixel);
            G = Color.green(pixel);
            B = Color.blue(pixel);
            R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }
    return bmOut;
}

内容的提问来源于stack exchange,提问作者Java_code99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 08:54:07